profile = {"name": "xiaoming", "age": 27}
ext_info = {"gender": "male"}
profile.update(ext_info)
print(profile)
{‘name’: ‘xiaoming’, ‘age’: 27, ‘gender’: ‘male’}
如果想使用 update 这种最简单、最地道原生的方法,但又不想更新到自己身上,而是生成一个新的对象,那请使用深拷贝。
profile = {"name": "xiaoming", "age": 27}
ext_info = {"gender": "male"}
from copy import deepcopy
full_profile = deepcopy(profile)
full_profile.update(ext_info)
print(full_profile)
{‘name’: ‘xiaoming’, ‘age’: 27, ‘gender’: ‘male’}
profile = {"name": "xiaoming", "age": 27}
ext_info = {"gender": "male"}
full_profile01 = {**profile, **ext_info}
print(full_profile01)
full_profile02 = dict(**profile, **ext_info)
print(full_profile02)
{‘name’: ‘xiaoming’, ‘age’: 27, ‘gender’: ‘male’}
正好我们字典也是可迭代对象,自然就可以想到,可以使用 itertools.chain() 函数先将多个字典(可迭代对象)串联起来,组成一个更大的可迭代对象,然后再使用 dict 转成字典。
import itertools
profile = {"name": "xiaoming", "age": 27}
ext_info = {"gender": "male"}
dict(itertools.chain(profile.items(), ext_info.items()))
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}
from collections import ChainMap
profile = {"name": "xiaoming", "age": 27}
ext_info = {"gender": "male"}
dict(ChainMap(profile, ext_info))
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}
使用 ChainMap 有一点需要注意,当字典间有重复的键时,只会取第一个值,排在后面的键值并不会更新掉前面的(使用 itertools 就不会有这个问题)。
from collections import ChainMap
profile = {"name": "xiaoming", "age": 27}
ext_info={"age": 30}
dict(ChainMap(profile, ext_info))
{'name': 'xiaoming', 'age': 27}
利用这一点,也可以将它用于字典的合并,只不过得绕个弯子,有点不好理解。
你得先利用 items 方法将 dict 转成 dict_items,再对这两个 dict_items 取并集,最后利用 dict 函数,转成字典。
profile = {"name": "xiaoming", "age": 27}
ext_info = {"gender": "male"}
full_profile = dict(profile.items() | ext_info.items())
full_profile
{'gender': 'male', 'age': 27, 'name': 'xiaoming'}
当然了,你如果嫌这样太麻烦,也可以简单点,直接使用 list 函数再合并(示例为 Python 3.x )
profile = {"name": "xiaoming", "age": 27}
ext_info = {"gender": "male"}
dict(list(profile.items()) + list(ext_info.items()))
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}
那就是列表解析式,集合解析式和字典解析式,通常是 Python 发烧友的最爱,那么今天的主题:字典合并,字典解析式还能否胜任呢?
当然可以,具体示例代码如下:
profile = {"name": "xiaoming", "age": 27}
ext_info = {"gender": "male"}
{k:v for d in [profile, ext_info] for k,v in d.items()}
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}
profile = {"name": "xiaoming", "age": 27}
ext_info = {"gender": "male"}
>>> profile | ext_info
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}
ext_info | profile
{'gender': 'male', 'name': 'xiaoming', 'age': 27}
除了 | 操作符之外,还有另外一个操作符 |=,类似于原地更新。
ext_info |= profile
ext_info
{'gender': 'male', 'name': 'xiaoming', 'age': 27}
profile |= ext_info
print(profile)
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}