Skip to main content
 首页 » 编程设计

python之在python中将多个词典转换为单个词典

2024年12月31日9pander-it

我有多个字典及其键和值,我想分配(将它们全部转移到一个新的空字典并保留所有键和值。 注意:我检查的其他问题有相同大小的字典

n = {} 
x = {'six':6,'thirteen':13,'fifty five':55} 
y = {'two': 2, 'four': 4, 'three': 3, 'one': 1, 'zero': 0,'ten': 10} 
z = {'nine': 9, 'four': 4, 'three': 3, 'eleven': 11, 'zero': 0, 'seven':7} 

请您参考如下方法:

ChainMap

对于许多用例,collections.ChainMap 就足够了并且高效(假设 Python 3.x):

from collections import ChainMap 
 
n = ChainMap(x, y, z) 
 
n['two']       # 2 
n['thirteen']  # 13 

如果你需要字典,只需在 ChainMap 对象上调用 dict 即可:

d = dict(n) 

字典解包

使用 Python 3.x(PEP448),您可以在定义新字典时解压字典:

d = {**x, **y, **z} 

相关:How to merge two dictionaries in a single expression?