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).
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]}
After defining
from itertools import *
def group(iterable, key, value = lambda x: x):
return dict((k, list(map(value, values))) for k, values in groupby(sorted(iterable, key = key), key))
use group(l, key = lambda x: x[0], value = lambda x: x[1]))
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With