在Python中将元组列表转换为Dict [英] Converting a List of Tuples into a Dict in Python

查看:741
本文介绍了在Python中将元组列表转换为Dict的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的元组列表:

I have a list of tuples like this:

[
('a', 1),
('a', 2),
('a', 3),
('b', 1),
('b', 2),
('c', 1),
]

我想迭代这个键通过第一个项目,所以例如我可以打印如下:

I want to iterate through this keying by the first item, so for example I could print something like this:

a 1 2 3
b 1 2
c 1

如果不保留项目来跟踪第一个项目,我该怎么做与我循环的元组一样。这感觉很混乱(加上我必须排序列表开始)...

How would I go about doing this without keeping an item to track whether the first item is the same as I loop round the tuples. This feels rather messy (plus I have to sort the list to start with)...

谢谢,

Dan

推荐答案

l = [
('a', 1),
('a', 2),
('a', 3),
('b', 1),
('b', 2),
('c', 1),
]

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

产生:

{'a': [1, 2, 3], 'c': [1], 'b': [1, 2]}

这篇关于在Python中将元组列表转换为Dict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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