简体   繁体   English

Python 2.7:附加到字典键的列表值

[英]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? 我想创建一个包含键列表值的字典,我怎样才能用字典理解呢?

ie: 即:

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

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! 但请注意,这是非常低效的,因为它将循环整个列表n+1次!

Better use just a plain-old for loop: 更好地使用一个普通的for循环:

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

Alternatively, you could also use itertools.groupy (as discovered by yourself): 或者,您也可以使用itertools.groupy (由您自己发现):

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]} 在所有情况下, d最终为{1: [2, 3, 4], 2: [1, 2, 3]}

You could use defaultdict from collections module. 您可以使用collections模块中的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]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM