列表到每个键具有多个值的字典转换? [英] list to dictionary conversion with multiple values per key?

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

问题描述

我有一个包含键/值的Python列表:

I have a Python list which holds pairs of key/value:

l=[ [1, 'A'], [1, 'B'], [2, 'C'] ]

将列表转换为字典,其中每个键的多个值将被聚合成一个元组:

I want to convert the list into a dictionary, where multiple values per key would be aggregated into a tuple:

{ 1:('A', 'B'), 2:('C',) }

迭代解决方案是微不足道的: / p>

The iterative solution is trivial:

l=[ [1, 'A'], [1, 'B'], [2, 'C'] ]
d={}
for pair in l:
    if d.has_key(pair[0]):
        d[pair[0]]=d[pair[0]]+tuple(pair[1])
    else:
        d[pair[0]]=tuple(pair[1])

print d

{1: ('A', 'B'), 2: ('C',)}

是否有更优雅的Pythonic解决方案?

Is there a more elegant, Pythonic solution for this task?

推荐答案

from collections import defaultdict

d1 = defaultdict(list)

for k, v in l:
    d1[k].append(v)

d = dict((k, tuple(v)) for k, v in d1.iteritems())

d 现在包含 {1:('A','B'),2:('C',)}

d1 是一个临时的defaultdict,列表为值,将转换为元组最后一行。这样你就会追加到列表中,而不是在主循环中重新创建元组。

d1 is a temporary defaultdict with lists as values, which will be converted to tuples in the last line. This way you are appending to lists and not recreating tuples in the main loop.

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

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