Python 定义字典为默认值的 Defaultdict 在键之间共享相同的字典
Python Defaultdict with defined dictionary as default value shares the same dictionary between keys
我在 defaultdict 中创建了一个嵌套的 defaultdict,我打算将其定义为 key:value 对作为默认值:
from collections import defaultdict
counter_format = {"correct": 0, "incorrect": 0}
userDict = defaultdict(lambda: defaultdict(lambda: counter_format))
但是,在嵌套的 defaultdicts 中更新字典中的各个键会导致此行为:
userDict['a'][1]['correct']+=1
userDict['b'][1]['correct']+=1
userDict['b'][2]['correct']+=1
userDict
现在看起来像:
defaultdict(<function <lambda> at 0x10ca85ee0>,
{'a': defaultdict(<function <lambda>.<locals>.<lambda> at 0x10cbc0430>,
{1: {'correct': 3,
'incorrect': 0}}),
'b': defaultdict(<function <lambda>.<locals>.<lambda> at 0x10cbc0b80>,
{1: {'correct': 3,
'incorrect': 0},
2: {'correct': 3,
'incorrect': 0}})})
要解决这个问题,您只需将 counter_format
字典结构移动到 lambda 中,这样每次您尝试访问最里面的缺失值时都会创建一个新的 counter_format
字典defaultdict
from collections import defaultdict
userDict = defaultdict(lambda:
defaultdict(lambda: {"correct": 0, "incorrect": 0})
)
userDict['a'][1]['correct']+=1
userDict['b'][1]['correct']+=4
userDict['b'][2]['correct']+=1
print(userdict)
defaultdict(<function <lambda> at 0x7f0f6cb38550>,
{'a': defaultdict(<function <lambda>.<locals>.<lambda> at 0x7f0f679424c0>,
{1: {'correct': 1, 'incorrect': 0}}),
'b': defaultdict(<function <lambda>.<locals>.<lambda> at 0x7f0f4caaa430>,
{1: {'correct': 4, 'incorrect': 0},
2: {'correct': 1, 'incorrect': 0}})})
我在 defaultdict 中创建了一个嵌套的 defaultdict,我打算将其定义为 key:value 对作为默认值:
from collections import defaultdict
counter_format = {"correct": 0, "incorrect": 0}
userDict = defaultdict(lambda: defaultdict(lambda: counter_format))
但是,在嵌套的 defaultdicts 中更新字典中的各个键会导致此行为:
userDict['a'][1]['correct']+=1
userDict['b'][1]['correct']+=1
userDict['b'][2]['correct']+=1
userDict
现在看起来像:
defaultdict(<function <lambda> at 0x10ca85ee0>,
{'a': defaultdict(<function <lambda>.<locals>.<lambda> at 0x10cbc0430>,
{1: {'correct': 3,
'incorrect': 0}}),
'b': defaultdict(<function <lambda>.<locals>.<lambda> at 0x10cbc0b80>,
{1: {'correct': 3,
'incorrect': 0},
2: {'correct': 3,
'incorrect': 0}})})
要解决这个问题,您只需将 counter_format
字典结构移动到 lambda 中,这样每次您尝试访问最里面的缺失值时都会创建一个新的 counter_format
字典defaultdict
from collections import defaultdict
userDict = defaultdict(lambda:
defaultdict(lambda: {"correct": 0, "incorrect": 0})
)
userDict['a'][1]['correct']+=1
userDict['b'][1]['correct']+=4
userDict['b'][2]['correct']+=1
print(userdict)
defaultdict(<function <lambda> at 0x7f0f6cb38550>,
{'a': defaultdict(<function <lambda>.<locals>.<lambda> at 0x7f0f679424c0>,
{1: {'correct': 1, 'incorrect': 0}}),
'b': defaultdict(<function <lambda>.<locals>.<lambda> at 0x7f0f4caaa430>,
{1: {'correct': 4, 'incorrect': 0},
2: {'correct': 1, 'incorrect': 0}})})