我有一个词典列表:
dicty = [defaultdict(list)] * (2)
dicty
[defaultdict(list, {}), defaultdict(list, {})]
现在我想知道如何索引这些词典?
我试过了:
dicty[0][0].append('abc')
dicty
[defaultdict(list, {0: ['abc']}), defaultdict(list, {0: ['abc']})]
但是你可以看到它附加在两个词典中。我想学习如何附加到单个字典中。
答案 0 :(得分:2)
您可以使用:
dicty = [defaultdict(list) for _ in range(2)]
使用[defaultdict(list)] * (2)
时,所有的词汇都指向内存中的同一个对象。
答案 1 :(得分:1)
from collections import defaultdict
""" Here, you are saying that you wish to add twice "defaultdict(list)".
These are the same objects. You are just duplicating the same one with *
"""
dicty = [defaultdict(list)] * (2)
dicty[0][0].append('abc')
print dicty
print dicty[0] is dicty[1], '\n'
""" However, here : you are creating two distinct dictionnaries.
"""
dicty = []
for _ in range(2):
dicty.append(defaultdict(list))
dicty[0][0].append('abc')
print dicty
print dicty[0] is dicty[1]
# outputs :
#[defaultdict(<type 'list'>, {0: ['abc']}), defaultdict(<type 'list'>, {0: ['abc']})]
#True
#[defaultdict(<type 'list'>, {0: ['abc']}), defaultdict(<type 'list'>, {})]
#False