0

Say I have a list of dictionaries of unknown length and unknown - but consistent - schema, as follows. Note that the values are always lists of the same length.

res = [{'x': [2, 1], 'v': [49280, 536704]}, {'x': [1, 4], 'v': [12336, 340000]}, {'x': [5, 6], 'v': [524360, 151624]}, {'x': [7, 1], 'v': [94280, 81968]}, {'x': [1, 1], 'v': [241856, 335904]}, {'x': [7, 7], 'v': [463016, 598040]}, {'x': [2, 9], 'v': [606256, 422016]}, {'x': [1, 1], 'v': [151680, 1237120]}] 

Is there an efficient way to merge combine these together into a single dictionary? The final result for this example would be:

 {'x': [2, 1, 1, 4, 5, 6, 7, 1, 1, 1, 7, 7, 2, 9, 1, 1], 'v': [49280, 536704, 12336, 340000, 524360, 151624, 94280, 81968, 241856, 335904, 463016, 598040, 606256, 422016, 151680, 1237120]} 

Working solution

This works, but I wonder if a one-liner for this operation?

output_dct = {} for dct in res: for k, v in dct.items(): output_dct[k] = v if k not in output_dct.keys() else output_dct[k] + v 

2 Answers 2

2

A slightly better approach using dict.setdefault

Ex:

output_dct = {} for dct in res: for k, v in dct.items(): output_dct.setdefault(k, []).extend(v) 

or using collections.defaultdict

from collections import defaultdict output_dct = defaultdict(list) for dct in res: for k, v in dct.items(): output_dct[k].extend(v) print(output_dct) 

Output:

{'x': [2, 1, 1, 4, 5, 6, 7, 1, 1, 1, 7, 7, 2, 9, 1, 1], 'v': [49280, 536704, 12336, 340000, 524360, 151624, 94280, 81968, 241856, 335904, 463016, 598040, 606256, 422016, 151680, 1237120]} 
Sign up to request clarification or add additional context in comments.

Comments

1

A one-liner, you say? To the comprehension-mobile!

>>> {k: sum((d[k] for d in res), []) for d in res for k in d} {'x': [2, 1, 1, 4, 5, 6, 7, 1, 1, 1, 7, 7, 2, 9, 1, 1], 'v': [49280, 536704, 12336, 340000, 524360, 151624, 94280, 81968, 241856, 335904, 463016, 598040, 606256, 422016, 151680, 1237120]} 

(edit: practically speaking, I'd probably do this with a defaultdict like Rakesh did, because nested comprehensions are compact on the page but aren't necessarily obvious to other readers of the code.)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.