Python 2.7:附加到字典键的列表值 [英] Python 2.7: Appending to a list value of a dictionary key

查看:76
本文介绍了Python 2.7:附加到字典键的列表值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据:

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?

即:

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

推荐答案

你可以使用这个 dict-comprehension:

You can use this dict-comprehension:

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

但是请注意,这非常低效,因为它会循环整个列表 n+1 次!

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

最好只使用一个普通的 for 循环:

Better use just a plain-old for loop:

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

或者,您也可以使用 itertools.groupy(自行发现):

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}

在所有情况下,d 最终都是 {1: [2, 3, 4], 2: [1, 2, 3]}

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

这篇关于Python 2.7:附加到字典键的列表值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆