Python 2.7: Appending to a list value of a dictionary key

python, python-2.7

Solution

You can use this dict-comprehension:

d = {x: [v for u,v in data if u == x] for x,y in data}

Note, however, that this is pretty inefficient, as it will loop the entire list `n+1` times!

Better use just a plain-old `for` loop:

d = {}
for x,y in data:
    d.setdefault(x, []).append(y)

Alternatively, you could also use `itertools.groupy` (as discovered by yourself):

groups = itertools.groupby(sorted(data), key=lambda x: x[0])
d = {k: [g[1] for g in group] for k, group in groups}

In all cases, `d` ends up being `{1: [2, 3, 4], 2: [1, 2, 3]}`

Problem

I have the following data: ``` data = [(1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3)] ``` and I want to create a dictionary which contains key-list value, how can I do this with a dictionary comprehension? i.e.: ``` {1: [2,3,4] 2: [1,2,3] } ``` I have tried the following but the list gets overwritten on every iteration. ``` {x: [y] for x,y in data} ```

Original source