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.
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.
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.
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.
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.
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']}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With