Python创建一个列表字典
我想创建一个字典,字典里的值是列表。比如说:
{
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,]
处理这个问题的最佳方法是什么呢?理想情况下,添加元素应该“直接就能用”。有没有什么办法可以在我第一次创建列表时就表示我想要一个空列表的字典,即使我不知道每个键是什么?
7 个回答
41
你可以使用 setdefault
这个函数:
d = dict()
a = ['1', '2']
for i in a:
for j in range(int(i), int(i) + 2):
d.setdefault(j, []).append(i)
print d # prints {1: ['1'], 2: ['1', '2'], 3: ['2']}
这个名字听起来有点奇怪的 setdefault
函数的意思是:“获取这个键对应的值,如果这个键不存在,就添加这个值,然后返回它。”
正如其他人所说的,defaultdict
是一个更好、更现代的选择。不过,setdefault
在老版本的 Python(2.5 之前)中仍然很有用。
60
你可以用列表推导式来这样构建它:
>>> dict((i, range(int(i), int(i) + 2)) for i in ['1', '2'])
{'1': [1, 2], '2': [2, 3]}
至于你问题的第二部分,可以使用 defaultdict
>>> from collections import defaultdict
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
d[k].append(v)
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
315
你可以使用 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'])]