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

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

问题描述

我有一个包含键/值对的 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',)}

迭代解决方案很简单:

l = [[1, 'A'], [1, 'B'], [2, 'C']]
d = {}
for pair in l:
    if pair[0] in d:
        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.items())

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天全站免登陆