Julius Kunze Julius Kunze - 1 month ago 5
Python Question

Group list to dictionary in Python

Given the list

l = [('a', 1), ('b', 2), ('a', 1), ('a', 2), ('c', 5), ('b', 3)]


how do I get the dictionary

{'a': [1, 1, 2], 'c': [5], 'b': [2, 3]}


in Python?

Edit: I was looking for a functional solution (using only 1 expression).

Answer

You may use the collections.defaultdict(). Alternatively, in case you do not want to import collections , you may achieve the same behavior with normal dict using dict.setdefault() as:

>>> my_dict = {}
>>> l = [('a', 1), ('b', 2), ('a', 1), ('a', 2), ('c', 5), ('b', 3)]
>>> for k, v in l:
...     my_dict.setdefault(k, []).append(v)
...
>>> my_dict
{'a': [1, 1, 2], 'c': [5], 'b': [2, 3]}
Comments