我想创建一个字典,其值是列表。例如:
{
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
循环之前不知道我需要的 key 。例如:
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,]
处理此问题的最佳方法是什么?理想情况下,追加将“正常工作”。有没有什么方法可以表达我想要一个空列表的字典,即使我在第一次创建列表时不知道每个键?
最佳答案
您可以使用 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创建列表字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/960733/