首页 > 解决方案 > 在python中使用for循环从其他dicts创建dict

问题描述

从现有字典中获取不同字典的好方法是什么?

例如我有这个:

x = {"x1":1,"x2":2,"x3":3}
y = {"y1":1,"y2":2,"y3":3}
z = {"z1":1,"z2":2,"z3":3}

我想要这个:

dict1 = {"x1":1,"y1":1,"z1":1}
dict2 = {"x2":2,"y2":2,"z2":2}
dict3 = {"x3":3,"y3":3,"z3":3}

假设我有更多的数据,我想要一个高效的快速方法,比如循环。

标签: pythondictionaryfor-loop

解决方案


您可以使用zip来实现这一点 -

a, b, c = [i for i in zip(x.items(), y.items(), z.items())]
dict1, dict2, dict3 = dict(a), dict(b), dict(c)

print(dict1)
print(dict2)
print(dict3)
{'x1': 1, 'y1': 1, 'z1': 1}
{'x2': 2, 'y2': 2, 'z2': 2}
{'x3': 3, 'y3': 3, 'z3': 3}

编辑:正如@Moinuddin 正确指出的那样,您可以通过将类型转换映射到 zip 对象来将其写在一行中。

dict1, dict2, dict3 = map(dict, zip(x.items(), y.items(), z.items()))

推荐阅读