回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>如何在一个<strong>单个表达式中获得字典
其中一个键值对已添加到子字典中
在输入字典里?输入字典应该保持不变。它
可以假定子字典确实存在,并且新的键值对不在子字典中。在</p>
<p><strong>更新2</strong>(有关“SOsurvivalConditions”等的定义,请参见下文):</p>
<p>最简洁的方法是:</p>
<pre><code>(SOsurvivalConditions['firstCondition'].setdefault('synonym', 'A modern form of RTFM is: Google It.'), SOsurvivalConditions)[-1]
</code></pre>
<p><strong>更新1</strong>:</p>
<p>这符合给定的要求,并且没有
修改输入字典的副作用:</p>
^{pr2}$
<p>然而,更简洁(但仅限于声明)的方法可以
与助手功能相适应,例如:</p>
<pre><code>import copy
def dictDeepAdd(inputDict, dictKey, newKey, newValue):
"""
Adds new key-value pair to a sub-dictionary and
returns a new version of inputDict.
dictKey is the key in inputDict for which a new
key-value pair is added.
Side-effect: none (does not change inputDict).
"""
toReturn = copy.deepcopy(inputDict)
toReturn[dictKey][newKey] = newValue
return toReturn
dictDeepAdd(
SOsurvivalConditions,
'firstCondition',
'synonym',
'A modern form of RTFM is: Google It.'
)
</code></pre>
<hr/>
<p>例如:</p>
<pre><code>goodStyle = \
{
'answer': 'RTFM responses are not acceptable on Stack Overflow - Joel Spolsky has repeatedly said so in the Stack Overflow podcasts.',
'RTFM' : 'RTFM is, in the less offensive version, an abbreviation for Read The Fine Manual.',
}
SOsurvivalConditions = \
{
'moodImperative' : 'be happy',
'firstCondition' : goodStyle,
}
</code></pre>
<p>SOsurvivalConditions中的“firstCondition”现在有两个键值对。
一个新的键值对(“synonym”,“RTFM的现代形式是:googleit”),
需要追加,并且结果应该在单个表达式中可用。在</p>
<p>这是可行的(一行,但在这里分成几行):</p>
<pre><code>{
'moodImperative': SOsurvivalConditions['moodImperative'],
'firstCondition' :
dict(
SOsurvivalConditions['firstCondition'],
synonym = 'A modern form of RTFM is: Google It.'
)
}
</code></pre>
<p>并返回:</p>
<pre><code>{'moodImperative': 'be happy',
'firstCondition':
{'answer': 'RTFM responses are not acceptable on Stack Overflow - Joel Spolsky has repeatedly said so in the Stack Overflow podcasts.',
'RTFM': 'RTFM is, in the less offensive version, an abbreviation for Read The Fine Manual.',
'synonym': 'A modern form of RTFM is: Google It.'
}
}
</code></pre>
<p>但是这里面有很多冗余
表达式-所有键都重复。“firstCondition”出现两次。还有别的吗
优雅的方式?在</p>
<p>(这里的数据结构的名称和内容都是虚构的,但代表了我今天遇到的一个真正的问题。Python版本:2.6.2.)。在</p>