将元组列表转换成字典 [英] Converting a list of tuples into a dict

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

问题描述

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

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 around the tuples? This feels rather messy (plus I have to sort the list to start with)...

推荐答案

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

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

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