Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a list of dictionaries to a dictionary of lists in Python?

It may be a classical question in Python, but I haven't found the answer yet.

I have a list of dictionaries, these dictionaries have similar keys. It looks like this:

 [{0: myech.MatchingResponse at 0x10d6f7fd0, 
   3: myech.MatchingResponse at 0x10d9886d0,
   6: myech.MatchingResponse at 0x10d6f7d90,
   9: myech.MatchingResponse at 0x10d988ad0},
  {0: myech.MatchingResponse at 0x10d6f7b10,
   3: myech.MatchingResponse at 0x10d6f7f90>}]

I would like to get a new dictionary with [0,3,6,9] as keys, and lists of " myech.MatchingResponse" as values.

Of course I can do this using a simple loop but I was wondering if there is a more efficient solution.

like image 984
lizzie Avatar asked Jul 12 '12 11:07

lizzie


People also ask

How do I convert a list of dictionaries in Python?

Since python dictionary is unordered, the output can be in any order. To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.

Can dictionary be converted to list in Python?

In Python, a dictionary provides method items() which returns an iterable sequence of all elements from the dictionary. The items() method basically converts a dictionary to a list along with that we can also use the list() function to get a list of tuples/pairs.

How do you convert a dictionary into a list?

To convert dictionary values to list sorted by key we can use dict. items() and sorted(iterable) method. Dict. items() method always returns an object or items that display a list of dictionaries in the form of key/value pairs.

Can you nest a dictionary in a list?

You can have dicts inside of a list. The only catch is that dictionary keys have to be immutable, so you can't have dicts or lists as keys.


1 Answers

It's possible to do this with dict comprehension as well ... could be one line, but I've kept it as two lines for clarity. :)

from itertools import chain

all_keys = set(chain(*[x.keys() for x in dd]))
print {k : [d[k] for d in dd if k in d] for k in all_keys}

Results in:

{0: ['a', 'x'], 9: ['d'], 3: ['b', 'y'], 6: ['c']}
like image 67
Maria Zverina Avatar answered Sep 25 '22 11:09

Maria Zverina