将具有重复键的列表转换为列表字典 [英] Convert a list with repeated keys to a dictionary of lists

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

问题描述

我与重复的键关联为list

l = [(1, 2), (2, 3), (1, 3), (2, 4)]

并且我想要一个dict且具有list值:

and I want a dict with list values:

d = {1: [2, 3], 2: [3, 4]}

我能做得更好吗?

for (x,y) in l:
  try:
    z = d[x]
  except KeyError:
    z = d[x] = list()
  z.append(y)

推荐答案

您可以使用 dict.setdefault()方法为缺少的键提供默认的空列表:

You can use the dict.setdefault() method to provide a default empty list for missing keys:

for x, y in l:
    d.setdefault(x, []).append(y)

,或者您可以使用 defaultdict()对象为缺少的对象创建空列表按键:

or you could use a defaultdict() object to create empty lists for missing keys:

from collections import defaultdict

d = defaultdict(list)
for x, y in l:
    d[x].append(y)

但是要关闭自动生存行为,您必须将default_factory属性设置为None:

but to switch off the auto-vivication behaviour you'd have to set the default_factory attribute to None:

d.default_factory = None  # switch off creating new lists

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

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