x=[{'a':1,'b':2},{'a':6,'b':5},{'a':3,'b':4}]
y={'a':[1,6,3],'b':[2,5,4]}
x is a list of dicts, where all dicts have same keys, now I want to merge the values to a list, as shown in the example, is there a fast implementation?
x=[{'a':1,'b':2},{'a':6,'b':5},{'a':3,'b':4}]
y={'a':[1,6,3],'b':[2,5,4]}
x is a list of dicts, where all dicts have same keys, now I want to merge the values to a list, as shown in the example, is there a fast implementation?
If all dicts in x
are guaranteed to have the same keys, you can do:
y = {k: [d[k] for d in x] for k in d[0]}
If not, you'll have to find the union of those first,
keys = {k for d in x for k in d.keys()}
Then iterate over that instead.
y = {k: [d[k] for d in x if k in d] for k in keys}
More verbose, you could write:
y = dict()
for d in x:
for k, v in d.items():
y.setdefault(k, []).append(v)