Python 创建列表字典 [英] Python creating a dictionary of lists

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

问题描述

我想创建一个字典,其值为列表.例如:

<代码>{1: ['1'],2: ['1','2'],3: ['2']}

如果我这样做:

d = dict()a = ['1', '2']因为我在一个:对于范围内的 j(int(i), int(i) + 2):d[j].append(i)

我收到一个 KeyError,因为 d[...] 不是一个列表.在这种情况下,我可以在分配 a 后添加以下代码来初始化字典.

 for x in range(1, 4):d[x] = 列表()

有没有更好的方法来做到这一点?假设在进入第二个 for 循环之前,我不知道我将需要的密钥.例如:

类关系:scope_list = list()...d = 字典()对于relation_list 中的关系:对于relation.scope_list 中的scope_item:d[scope_item].append(relation)

替代方案是替换

d[scope_item].append(relation)

如果 d.has_key(scope_item):d[scope_item].append(relation)别的:d[scope_item] = [关系,]

处理这个问题的最佳方法是什么?理想情况下,附加将正常工作".有什么方法可以表达我想要一个空列表的字典,即使我在第一次创建列表时不知道每个键?

解决方案

您可以使用 defaultdict:

<预><代码>>>>从集合导入 defaultdict>>>d = defaultdict(列表)>>>a = ['1', '2']>>>因为我在一个:...对于范围内的 j(int(i), int(i) + 2):... d[j].append(i)...>>>ddefaultdict(, {1: ['1'], 2: ['1', '2'], 3: ['2']})>>>d.items()[(1, ['1']), (2, ['1', '2']), (3, ['2'])]

I want to create a dictionary whose values are lists. For example:

{
  1: ['1'],
  2: ['1','2'],
  3: ['2']
}

If I do:

d = dict()
a = ['1', '2']
for i in a:
    for j in range(int(i), int(i) + 2): 
        d[j].append(i)

I get a KeyError, because d[...] isn't a list. In this case, I can add the following code after the assignment of a to initialize the dictionary.

for x in range(1, 4):
    d[x] = list()

Is there a better way to do this? Lets say I don't know the keys I am going to need until I am in the second for loop. For example:

class relation:
    scope_list = list()
...
d = dict()
for relation in relation_list:
    for scope_item in relation.scope_list:
        d[scope_item].append(relation)

An alternative would then be replacing

d[scope_item].append(relation)

with

if d.has_key(scope_item):
    d[scope_item].append(relation)
else:
    d[scope_item] = [relation,]

What is the best way to handle this? Ideally, appending would "just work". Is there some way to express that I want a dictionary of empty lists, even if I don't know every key when I first create the list?

解决方案

You can use defaultdict:

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> a = ['1', '2']
>>> for i in a:
...   for j in range(int(i), int(i) + 2):
...     d[j].append(i)
...
>>> d
defaultdict(<type 'list'>, {1: ['1'], 2: ['1', '2'], 3: ['2']})
>>> d.items()
[(1, ['1']), (2, ['1', '2']), (3, ['2'])]

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

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