Search code examples
pythondictionarynested

Python: Change just one entry in nested dictionary


Basically I just want to change nested dictionaries but in my code I change multiple sublevel dictionaries at once.

So I have a nested dictionary which looks this way

d1 = {'a': {0: [1,2], 1: [1,2]}, 'b': {0: [1,2], 1: [1,2]}}

Then I want to add an entry

d1['a'][2] = [2,2]

And then I get what I want

{'a': {0: [1, 2], 1: [1, 2], 2: [2, 2]}, 'b': {0: [1, 2], 1: [1, 2]}}

But when I want to create my dictionary like this (and I need it that way, because my dict has to have different lengths and so on)

d2 = dict.fromkeys(['a','b'], dict.fromkeys([0,1], [1,2]))

I will get

{'a': {0: [1, 2], 1: [1, 2], 2: [2, 2]}, 'b': {0: [1, 2], 1: [1, 2], 2: [2, 2]}}

so it will add the new dictionary entry to both lower level dictionaries. Why does it do this and how can I prevent this? I tried now a lot of stuff but I cant manage to solve this... Maybe you can help?


Solution

  • You can check answers here:

    Unwanted behaviour from dict.fromkeys

    If dict().fromkeys() all point to the same object, what purpose does the default value argument serve?

    In particular, if you try:

    dict.fromkeys(['a','b'], object())
    

    you will see that the adresses are the same:

    {'a': <object at 0x2fa88dfebe0>, 'b': <object at 0x2fa88dfebe0>}