我想创建一个值为列表的字典。例如:
{
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赋值后,我可以添加以下代码来初始化字典。
for x in range(1, 4):
d[x] = list()
有没有更好的方法做到这一点?比方说,在第二个for
循环中,我不知道我需要哪些键。例如:
class relation:
scope_list = list()
...
d = dict()
for relation in relation_list:
for scope_item in relation.scope_list:
d[scope_item].append(relation)
把 替换成其他内容也是一种选择。d[scope_item].append(relation)
与之配合if d.has_key(scope_item):
d[scope_item].append(relation)
else:
d[scope_item] = [relation,]
最好的处理方式是什么?理想情况下,添加应该“只是工作”。是否有一种表达方式,可以让我在第一次创建列表时就获取到一个空列表字典,即使我不知道每个键名?
collections
模块下的其他字典也是这样工作的,例如collections.OrderedDict
。 - txsaw1NameError: name 'a' is not defined
- S Andrew