我想将两个词典融入一个新的词典。
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = merge(x, y)
>>> z
{'a': 1, 'b': 3, 'c': 4}
每当两个字典中都有一个关键 k 时,只应保留 y(k) 的值。
我想将两个词典融入一个新的词典。
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = merge(x, y)
>>> z
{'a': 1, 'b': 3, 'c': 4}
每当两个字典中都有一个关键 k 时,只应保留 y(k) 的值。
当前回答
这是如此愚蠢,即.update 没有回报,我只是使用一个简单的助理功能来解决问题:
def merge(dict1,*dicts):
for dict2 in dicts:
dict1.update(dict2)
return dict1
例子:
merge(dict1,dict2)
merge(dict1,dict2,dict3)
merge(dict1,dict2,dict3,dict4)
merge({},dict1,dict2) # this one returns a new copy
其他回答
重复 / 深度更新 a dict
def deepupdate(original, update):
"""
Recursively update a dict.
Subdict's won't be overwritten but also updated.
"""
for key, value in original.iteritems():
if key not in update:
update[key] = value
elif isinstance(value, dict):
deepupdate(value, update[key])
return update
示威:
pluto_original = {
'name': 'Pluto',
'details': {
'tail': True,
'color': 'orange'
}
}
pluto_update = {
'name': 'Pluutoo',
'details': {
'color': 'blue'
}
}
print deepupdate(pluto_original, pluto_update)
结果:
{
'name': 'Pluutoo',
'details': {
'color': 'blue',
'tail': True
}
}
谢谢Radnaw的编辑。
如果你認為Lambdas是壞的,那麼不要再閱讀。 如要求,你可以用一個表達寫下快速和記憶效益的解決方案:
x = {'a':1, 'b':2}
y = {'b':10, 'c':11}
z = (lambda a, b: (lambda a_copy: a_copy.update(b) or a_copy)(a.copy()))(x, y)
print z
{'a': 1, 'c': 11, 'b': 10}
print x
{'a': 1, 'b': 2}
如上所述,使用两行或写一个函数可能是一个更好的方式去。
x = {'a':1, 'b': 2}
y = {'b':10, 'c': 11}
z = dict(x.items() + y.items())
print z
对于两个字典中的关键物品(“b”),您可以通过将最后一个放在输出中来控制哪个。
在您的情况下,您可以:
z = dict(list(x.items()) + list(y.items()))
因此,如您所需,将最终定位定位为z,并使关键b的值由第二(y)定位的值正确上调:
>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = dict(list(x.items()) + list(y.items()))
>>> z
{'a': 1, 'c': 11, 'b': 10}
如果您使用 Python 2, 您甚至可以删除列表() 通话。
>>> z = dict(x.items() + y.items())
>>> z
{'a': 1, 'c': 11, 'b': 10}
如果您使用 Python 版本 3.9.0a4 或更高版本,则可以直接使用:
x = {'a':1, 'b': 2}
y = {'b':10, 'c': 11}
z = x | y
print(z)
{'a': 1, 'c': 11, 'b': 10}
在Python 3.8发布时,将有一个新的选项(计划于2019年10月20日),感谢PEP 572:分配表达式。 新的分配表达式操作员:= 允许您分配副本的结果,并且仍然使用它来呼叫更新,留下组合代码一个单一表达式,而不是两个陈述,改变:
newdict = dict1.copy()
newdict.update(dict2)
到:
(newdict := dict1.copy()).update(dict2)
(newdict := dict1.copy()).update(dict2) or newdict
newdict = {**dict1, **dict2}
脱包方法更清晰(对于任何人都知道一般的脱包,首先,你应该),不需要一个名字的结果(因此,它是更紧密的,当构建一个暂时的,即时转移到一个功能或包含在一个名单 / 双字或类似),并且几乎肯定更快,也是(在CPython上)相当于:
newdict = {}
newdict.update(dict1)
newdict.update(dict2)
它也更可扩展,因为结合三个法则是显而易见的:
newdict = {**dict1, **dict2, **dict3}
(newdict := dict1.copy()).update(dict2), newdict.update(dict3)
或沒有暫時的九個,但以真實的測試,每個九個結果:
(newdict := dict1.copy()).update(dict2) or newdict.update(dict3)