Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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}
like image 511
Har Avatar asked Feb 10 '23 20:02

Har


1 Answers

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]}

like image 95
tobias_k Avatar answered Feb 13 '23 10:02

tobias_k