[英]Convert a dictionary of dictionaries to dictionary of lists
I have a dictionary of dictionaries:我有一本字典:
d = {"a": {"x":1, "y":2, "z":3}, "b": {"x":2, "y":3, "z":4}, "c": {"x":3, "y":4, "z":5}}
And I want to convert it to:我想将其转换为:
new_d = {"x":[1, 2, 3], "y": [2, 3, 4], "z": [3, 4, 5]}
The requirement is that new_d[key][i]
and new_d[another_key][i]
should be in the same sub-dictionary of d
.要求是
new_d[key][i]
和new_d[another_key][i]
应该在d
的同一个子字典中。
So I created new_d = {}
and then:所以我创建了
new_d = {}
然后:
for key in d.values()[0].keys():
new_d[key] = [d.values()[i][key] for i in range(len(d.values()))]
This gives me what I expected, but I am just wondering if there are some built-in functions for this operation or there are better ways to do it.这给了我预期的结果,但我只是想知道这个操作是否有一些内置函数或者有更好的方法来做到这一点。
There is no built-in function for this operation, no.这个操作没有内置函数,没有。 I'd just loop over
values
directly :我只是直接循环
values
:
new_d = {}
for sub in d.itervalues(): # Python 3: use d.values()
for key, value in sub.iteritems(): # Python 3: use d.items()
new_d.setdefault(key, []).append(value)
This avoids creating a new list for the dict.values()
call each time.这避免了每次为
dict.values()
调用创建一个新列表。
Note that dictionaries have no order.请注意,字典没有顺序。 The values in the resulting lists are going to fit your criteria however;
然而,结果列表中的值将符合您的标准; they'll be added in the same order for each of the keys in
new_d
:对于
new_d
每个键,它们将以相同的顺序添加:
>>> d = {"a": {"x":1, "y":2, "z":3}, "b": {"x":2, "y":3, "z":4}, "c": {"x":3, "y":4, "z":5}}
>>> new_d = {}
>>> for sub in d.values():
... for key, value in sub.items():
... new_d.setdefault(key, []).append(value)
...
>>> new_d
{'x': [1, 2, 3], 'y': [2, 3, 4], 'z': [3, 4, 5]}
If you like dictionary and list comprehensions ...如果你喜欢字典和列表推导......
d1 = {"a": {"x": 1, "y": 2, "z": 3},
"b": {"x": 2, "y": 3, "z": 4},
"c": {"x": 3, "y": 4, "z": 5}}
dl1 = {kl: [v for di in d1.values() for k, v in di.items() if k == kl]
for di in d1.values() for kl in di.keys()}
print(dl1)
And yields the results hoped for ...并产生预期的结果......
{'x': [1, 2, 3], 'y': [2, 3, 4], 'z': [3, 4, 5]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.