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

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

问题描述

我正在寻找一种转换像这样的元组列表的方法:

I'm looking for a way to convert a list of tuples like this:

[(1,4),(2,4),(3,4),(4,15),(5,15),(6,23),(7,23),(8,23),(9,15),(10,23),(11,15),(12,15)]

放入这样的字典中:

{4:[1,2,3] ,15:[4,5,9,11,12], 23:[6,7,8,10]}

每个元组的第二个元素成为字典键,并且与该键关联的所有第一个元组元素都存储在值列表中.

The second element from each tuple becomes a dictionary key, and all the first tuple elements associated with that key are stored in a value list.

您能告诉我该怎么做吗?

Can you show me how that can be done?

推荐答案

>>> from collections import defaultdict
>>> l= [(1,4),(2,4),(3,4),(4,15),(5,15),(6,23),(7,23),(8,23),(9,15),(10,23),(11,15),(12,15)]
>>> d= defaultdict( list )
>>> for v, k in l:
...     d[k].append(v)
... 
>>> d
defaultdict(<type 'list'>, {23: [6, 7, 8, 10], 4: [1, 2, 3], 15: [4, 5, 9, 11, 12]})
>>> [ {k:d[k]} for k in sorted(d) ]
[{4: [1, 2, 3]}, {15: [4, 5, 9, 11, 12]}, {23: [6, 7, 8, 10]}]

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

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