[英]Convert a list of tuples with repeated keys to a dictionary of lists
I have an association list
with repeated keys:我有一个带有重复键的关联
list
:
l = [(1, 2), (2, 3), (1, 3), (2, 4)]
and I want a dict
with list
values:我想要一个带有
list
值的dict
:
d = {1: [2, 3], 2: [3, 4]}
Can I do better than:我能做得更好吗:
for (x,y) in l:
try:
z = d[x]
except KeyError:
z = d[x] = list()
z.append(y)
You can use thedict.setdefault()
method to provide a default empty list for missing keys:您可以使用
dict.setdefault()
方法为缺少的键提供默认的空列表:
for x, y in l:
d.setdefault(x, []).append(y)
or you could use a defaultdict()
object to create empty lists for missing keys:或者您可以使用
defaultdict()
对象为缺少的键创建空列表:
from collections import defaultdict
d = defaultdict(list)
for x, y in l:
d[x].append(y)
but to switch off the auto-vivication behaviour you'd have to set the default_factory
attribute to None
:但是要关闭自动激活行为,您必须将
default_factory
属性设置为None
:
d.default_factory = None # switch off creating new lists
You can use collections.defaultdict
:您可以使用
collections.defaultdict
:
d = collections.defaultdict(list)
for k, v in l:
d[k].append(v)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.