Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group list to dictionary in Python [duplicate]

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).

like image 620
Julius Kunze Avatar asked Sep 19 '25 08:09

Julius Kunze


2 Answers

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]}
like image 81
Moinuddin Quadri Avatar answered Sep 20 '25 23:09

Moinuddin Quadri


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])).

like image 43
Julius Kunze Avatar answered Sep 20 '25 23:09

Julius Kunze