Dict inside defaultdict being shared across keys

后端 未结 2 1346
盖世英雄少女心
盖世英雄少女心 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: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)
    

提交回复
热议问题