Python 2.7: adding a dictionary key to a list value

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 that contains the key list value, how can I do this with an understanding of the dictionary?

i.e:.

{1: [2,3,4]
 2: [1,2,3]
}

I tried the following, but the list is overwritten at each iteration.

{x: [y] for x,y in data}
+4
source share
2 answers

You can use this dictation:

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

Note, however, that this is rather inefficient, as it will loop through the entire list of n+1times!

Better to use a simple old loop for:

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

Alternatively, you can 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 dends{1: [2, 3, 4], 2: [1, 2, 3]}

+6

defaultdict .

>>> from collections import defaultdict
>>> data = [(1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3)]
>>> m = defaultdict(list)
>>> for i,j in data:
        m[i].append(j)


>>> m
defaultdict(<class 'list'>, {1: [2, 3, 4], 2: [1, 2, 3]})
>>> dict(m)
{1: [2, 3, 4], 2: [1, 2, 3]}
+2

All Articles