Combining Dictionaries Of Lists In Python

Viewed 27023

I have a very large collection of (p, q) tuples that I would like to convert into a dictionary of lists where the first item in each tuple is a key that indexes a list that contains q.

Example:

Original List: (1, 2), (1, 3), (2, 3)  
Resultant Dictionary: {1:[2, 3], 2:[3]}  

Furthermore, I would like to efficiently combine these dictionaries.

Example:

Original Dictionaries: {1:[2, 3], 2:[3]}, {1:[4], 3:[1]}  
Resultant Dictionary: {1:[2, 3, 4], 2:[3], 3:[1]}  

These operations reside within an inner loop, so I would prefer that they be as fast as possible.

Thanks in advance

6 Answers

A one-liner solution:

>>> a = {1:[2, 3], 2:[3]}
>>> b = {1:[4], 3:[1]}
>>>
>>> result = {key: a.get(key, []) + b.get(key, []) for key in (a.keys() | b.keys())}
>>> result
{1: [2, 3, 4], 2: [3], 3: [1]}
Related