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