在Python中将多个字典转换为单个字典

时间:2018-11-21 17:19:49

标签: python python-3.x dictionary

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

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}

3 个答案:

答案 0 :(得分:1)

ChainMap

在许多用例中,collections.ChainMap足够且有效(假设使用Python 3.x):

from collections import ChainMap

n = ChainMap(x, y, z)

n['two']       # 2
n['thirteen']  # 13

如果您需要字典,只需在dict对象上调用ChainMap

d = dict(n)

字典解包

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

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

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

答案 1 :(得分:0)

在这样的循环中使用dict自己的更新方法:

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}

n = {}
for e in [x,y,z]:
    n.update(e)

如果您只听几句话,那会很快。但是,如果您有多个字典(例如,超过20个),则最好使用locals()。

n = {}
for e in "xyz":
    n.update(locals()[e])

或者,如果您使用python3,有一种更简单的方法:

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

答案 2 :(得分:0)

我读过想要重复的键。 dict键是唯一的,因此在这种情况下,将数据转换为另一个数据结构,例如转换为元组。

your_first_dict = {"a":1, "b":2, "c":3}
your_second_dict = {"a":3, "b":4, "d":5}
list_of_tuples = [(key,your_first_dict[key]) for key in your_first_dict]
list_of_tuples += [(key,your_second_dict[key]) for key in your_second_dict]