Dict inside defaultdict being shared across keys

后端 未结 2 1323
盖世英雄少女心
盖世英雄少女心 2021-01-18 17:27

I have a dictionary inside a defaultdict. I noticed that the dictionary is being shared across keys and therefore it takes the values of the last write. How can I isolate th

2条回答
  •  无人及你
    2021-01-18 18:02

    When you do dict(defaults) you're not copying the inner dictionary, just making another reference to it. So when you change that dictionary, you're going to see the change everywhere it's referenced.

    You need deepcopy here to avoid the problem:

    import copy
    from collections import defaultdict
    defaults = {'a': 1, 'b': {}}
    dd = defaultdict(lambda: copy.deepcopy(defaults))
    

    Or you need to not use the same inner mutable objects in successive calls by not repeatedly referencing defaults:

    dd = defaultdict(lambda: {'a': 1, 'b': {}})
    

提交回复
热议问题