如何在单个表达式中获取一个字典,其中一个键值对已添加到某个输入字典中的子字典中?输入字典应保持不变.可以假设子字典确实存在并且新的键值对不在子字典中.
更新2(见下文"SOsurvivalConditions"的定义等):
最简洁的方法是:
(SOsurvivalConditions['firstCondition'].setdefault('synonym', 'A modern form of RTFM is: Google It.'), SOsurvivalConditions)[-1]
Run Code Online (Sandbox Code Playgroud)
更新1:
这符合给定的要求,没有修改输入字典的副作用:
dict((k,dict(v, synonym='A modern form of RTFM is: Google It.') if k == "firstCondition" else v) for k,v in SOsurvivalConditions.iteritems())
Run Code Online (Sandbox Code Playgroud)
但是,更简洁(但仅限于语句)的方式可以使用辅助函数进行调整,例如:
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.'
)
Run Code Online (Sandbox Code Playgroud)
这个例子:
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,
}
Run Code Online (Sandbox Code Playgroud)
SOsurvivalConditions中的'firstCondition'现在有两个键值对.需要附加新的键值对("同义词","现代形式的RTFM:Google It."),并且结果应该在单个表达式中可用.
这工作(一行,但在这里分成几个):
{
'moodImperative': SOsurvivalConditions['moodImperative'],
'firstCondition' :
dict(
SOsurvivalConditions['firstCondition'],
synonym = 'A modern form of RTFM is: Google It.'
)
}
Run Code Online (Sandbox Code Playgroud)
并返回:
{'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.'
}
}
Run Code Online (Sandbox Code Playgroud)
但是,此表达式中存在大量冗余 - 所有键都重复出现.'firstCondition'出现两次.有更优雅的方式吗?
(这里的数据结构的名称和内容是组成的,但代表了我今天遇到的一个真正的问题.Python版本:2.6.2.).
SOsurvivalConditions['firstCondition']['synonym'] = 'A modern form of RTM is: Google It.'
Run Code Online (Sandbox Code Playgroud)