-1
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?

Linghao.Chen
  • 103
  • 1
  • 1
  • 5
  • 1
    Does this answer your question? [How can I combine dictionaries with the same keys in python?](https://stackoverflow.com/questions/11533274/how-can-i-combine-dictionaries-with-the-same-keys-in-python) – Boris Verkhovskiy Dec 10 '19 at 02:59

1 Answers1

1

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)
Adam Smith
  • 52,157
  • 12
  • 73
  • 112
  • This implementation seems to contain 2 for loops thus has innecessary accesses. – Linghao.Chen Dec 10 '19 at 03:00
  • The original data structure is nested, so of course it takes nested loops to iterate over it. None of the accesses it does are unnecessary. – kaya3 Dec 10 '19 at 03:01
  • @Linghao.Chen you'll find that you need one `for` to obtain your list of possible keys, and another to find the values therein – Adam Smith Dec 10 '19 at 03:01
  • @kaya3 whoops typo (obviously :D). Thanks – Adam Smith Dec 10 '19 at 03:05
  • ...or just `d` (because you are iterating over the keys anyway). – Austin Dec 10 '19 at 03:05
  • @Austin yeah but `d.keys()` is more explicit and no less performant. Plus the alternative is `k for d in x for k in d` which makes me want to cry. Too many single-letter var names – Adam Smith Dec 10 '19 at 03:06