将字典词典转换为列表词典

s95*_*527 4 python dictionary python-2.7

我有字典词典:

d = {"a": {"x":1, "y":2, "z":3}, "b": {"x":2, "y":3, "z":4}, "c": {"x":3, "y":4, "z":5}}
Run Code Online (Sandbox Code Playgroud)

我想将其转换为:

new_d = {"x":[1, 2, 3], "y": [2, 3, 4], "z": [3, 4, 5]}
Run Code Online (Sandbox Code Playgroud)

要求是new_d[key][i]并且new_d[another_key][i]应该在的同一子词典中d

所以我创建了new_d = {}然后:

for key in d.values()[0].keys():
    new_d[key] = [d.values()[i][key] for i in range(len(d.values()))]
Run Code Online (Sandbox Code Playgroud)

这给了我期望的结果,但是我只是想知道此操作是否有一些内置函数,或者有更好的方法来实现。

Mar*_*ers 6

没有此操作的内置功能。我只是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)
Run Code Online (Sandbox Code Playgroud)

这样避免了dict.values()每次为呼叫创建一个新列表。

请注意,字典没有顺序。结果列表中的值将符合您的条件;将为它们中的每个键以相同的顺序添加它们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]}
Run Code Online (Sandbox Code Playgroud)