How do I convert a list of dictionaries to a dictionary of lists in Python?
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']}
import collections
result = collections.defaultdict(list)
for d in dictionaries:
for k, v in d.items():
result[k].append(v)
let's say your list is assigned to a variable called mylist.
mydic = {}
for dic in mylist:
for key, value in dic.items():
if key in mydic:
mydic[key].append(value)
else:
mydic[key] = [value]