【问题标题】:create dict from other dicts with for loop in python在python中使用for循环从其他dicts创建dict
【发布时间】:2021-01-02 23:08:42
【问题描述】:

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

例如我有这个:

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}

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

【问题讨论】:

  • 需要转置还是别的,输出比较混乱。
  • 你知道字典是无序的吗?
  • 不,我只想在新 dicts 中有 evry dict 的第一个、第二个和第三个值。
  • 我认为字典不是解决这个问题的最佳数据结构。字典是无序的。我会将值存储在数组xs = [1, 2, 3]ys=[2,3,2] ... 连接它们,进行转置并再次读取行...。

标签: python dictionary for-loop


【解决方案1】:

您可以使用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()))

【讨论】:

  • 另外值得一提的是,字典从 Python 3.7 开始维护插入顺序。在那之前,字典是无序的
猜你喜欢
  • 2021-11-27
  • 1970-01-01
  • 1970-01-01
  • 2013-05-28
  • 1970-01-01
  • 2021-07-25
  • 1970-01-01
  • 2018-11-02
  • 1970-01-01
相关资源
最近更新 更多