字典的Python列表 [英] Python list to dict

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

问题描述

我有一个庞大的清单,例如

I have a huge list like

['a', '2'] ['a', '1'] ['b', '3'] ['c', '2'] ['b', '1'] ['a', '1']['b', '1'] ['c', '2']['b', '3'] ['b', '1']

我想遍历此内容,并获得不同的第一项的第二项的编号输出:

I want to walk through this and get an output of number of each second item for a distinct first item:

{a:[2,1,1] b:[3,1,3,1] c:[2,2]}

推荐答案

data = [['a','2'],['a','1'],['b','3'],['c','2'],['b','1'],['a','1'],['b','1'],['c','2'],['b','3'],['b','1']]
result = {}
for key, value in data:
    result.setdefault(key, []).append(value)

结果:

>>> result
{'a': ['2', '1', '1'], 'c': ['2', '2'], 'b': ['3', '1', '1', '3', '1']}

与defaultdict相比,我更喜欢 dict.setdefault()普通字典,尝试访问不存在的键会引发异常,而不是给出值(在这种情况下为空列表).

I prefer dict.setdefault() over defaultdict because you end up with a normal dictionary, where attempting to access a key that doesn't exist raises an exception instead of giving a value (in this case an empty list).

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

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