简体   繁体   中英

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 .

So I created new_d = {} and then:

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 :

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.

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 :

>>> 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]}

List Comprehension Method

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]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM