gpt4 book ai didi

Python:深度附加到字典? - 在一个表达式中

转载 作者:太空狗 更新时间:2023-10-29 20:48:36 26 4
gpt4 key购买 nike

如何在单个表达式中获取字典其中一个键值对已添加到子字典在某些输入词典中?输入字典应保持不变。它可以假设子字典确实存在,并且新的键值对不在子字典中。

更新 2(“SOsurvivalConditions”等的定义见下文):

最简洁的方式是:

(SOsurvivalConditions['firstCondition'].setdefault('synonym', 'A modern form of RTFM is: Google It.'), SOsurvivalConditions)[-1]

更新 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())

然而更简洁(但仅声明)的方式可以使用辅助函数进行调整,例如:

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.'
)

示例:

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,
}

SOsurvivalConditions 中的“firstCondition”现在有两个键值对。一个新的键值对,('同义词','RTFM 的现代形式是:Google It。'),需要附加并且结果应该在单个表达式中可用。

这行得通(一行,但在这里分成几行):

{
'moodImperative': SOsurvivalConditions['moodImperative'],
'firstCondition' :
dict(
SOsurvivalConditions['firstCondition'],
synonym = 'A modern form of RTFM is: Google It.'
)
}

并返回:

{'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.'
}
}

但是这里有很多冗余表达式 - 所有键都重复。并且“firstCondition”出现了两次。有没有更优雅的方式?

(这里数据结构的名称和内容都是编造的,但是代表我今天遇到的一个真实问题。Python版本:2.6.2.)。

最佳答案

SOsurvivalConditions['firstCondition']['synonym'] = 'A modern form of RTM is: Google It.'

关于Python:深度附加到字典? - 在一个表达式中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1084678/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com