Python创建列表的字典 [英] Python creating a dictionary of lists
问题描述
我想创建一个值为列表的字典。例如:
I want to create a dictionary whose values are lists. For example:
{
1: ['1'],
2: ['1','2'],
3: ['2']
}
如果我这样做:
d = dict()
a = ['1', '2']
for i in a:
for j in range(int(i), int(i) + 2):
d[j].append(i)
我收到一个KeyError,因为d [...]不是列表。在这种情况下,我可以在分配a之后添加以下代码来初始化字典。
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)
与
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?
推荐答案
您可以使用 defaultdict :
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> 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屋!