Dict inside defaultdict being shared across keys

后端 未结 2 1320
盖世英雄少女心
盖世英雄少女心 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': {}})
    
    0 讨论(0)
  • 2021-01-18 18:14

    Your values all contain references to the same object from defaults: you rebuild the outer dict, but not the inner one. Just make a function that creates a new, separate object:

    def builder():
        return {'a': 1, 'b': {}}
    dd = defaultdict(builder)
    
    0 讨论(0)
提交回复
热议问题