合并两个字典并保留第一个字典的值 [英] Merge two dictionaries and persist the values of first dictionaries
问题描述
我有两个字典:
first = {"phone": {
"home": "(234) 442-4424"
},
"address":"xyz"
}
second = {"phone": {
"home": "(234) 442-4424",
"home1": "(234) 442-4424"
},
"address":{}
}
我想先合并两个字典,这意味着第一个字典不会丢失其先前的值,而只有丢失的键值会被添加到第一个字典中.
I want merge two dictionaries first over second, meaning the first dictionary doesn't lose its previous values and only the missing key values are added into first.
最终的字典应如下所示:
The final dictionary should look like this:
final = {"phone": {
"home": "(234) 442-4424",
"home1": "(234) 442-4424"
},
"address":"xyz"
}
如果我们使用字典列表,例如:-
Also what if when we use list of dictionaries like : -
first = {"phone": {
"home": "(234) 442-4424"
},
"address":[{"home":""},{"office":""}]
}
推荐答案
Update()
将起作用,只需复制第二个字典并应用第一个字典.因此,第一个的值将替换第二个的值,而不是相反的方法.
Update()
will work, simply copy the second dict and apply the first one. So the value of the first will replace the second and not the reverse way.
first = {"phone": {"home": "(234) 442-4424"},"address":"xyz"}
second = {"phone": {"home": "(234) 442-5555","home1": "(234) 442-4424"},"address":{}}
# recursive deep update you can find here: http://stackoverflow.com/a/3233356/956660
import collections
def update(d, u):
for k, v in u.iteritems():
if isinstance(v, collections.Mapping):
r = update(d.get(k, {}), v)
d[k] = r
else:
d[k] = u[k]
return d
third = second.copy()
update(third, first)
print(third)
{'phone':{'home':'(234)442-4424','home1':'(234)442-4424'},'address':'xyz'}
{'phone': {'home': '(234) 442-4424', 'home1': '(234) 442-4424'}, 'address': 'xyz'}
这篇关于合并两个字典并保留第一个字典的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!