Merges two or more dictionaries.
- Create a new
dict
and loop overdicts
, usingdictionary.update()
to add the key-value pairs from each one to the result.
代码实现
def merge_dictionaries(*dicts):
res = dict()
for d in dicts:
res.update(d)
return res
使用样例
ages_one = {
'Peter': 10,
'Isabel': 11,
}
ages_two = {
'Anna': 9
}
merge_dictionaries(ages_one, ages_two)
# { 'Peter': 10, 'Isabel': 11, 'Anna': 9 }
翻译自:https://www.30secondsofcode.org/python/s/merge-dictionaries