Home > Software engineering >  How to add dictionary inside of an another dictionary in Python
How to add dictionary inside of an another dictionary in Python

Time:11-06

I have been trying to add one of my dictionaries into another one. I did do that using the code below, but when I update one of the values, all off the values with the same name is also updated. How can I fix it?

Here is my code:


test_dict = {'count': 0}

D = {'emp1': {'name': test_dict, 'job': 'Mgr'},
     'emp2': {'name': test_dict, 'job': 'Dev'},
     'emp3': {'name': test_dict, 'job': 'Dev'}}

D['emp1']['name']['count']  = 1

print(D)

The output is this

{'emp1': {'name': {'count': 1}, 'job': 'Mgr'}, 'emp2': {'name': {'count': 1}, 'job': 'Dev'}, 'emp3': {'name': {'count': 1}, 'job': 'Dev'}}

when I should have this. How can I fix it?

{'emp1': {'name': {'count': 1}, 'job': 'Mgr'}, 'emp2': {'name': {'count': 0}, 'job': 'Dev'}, 'emp3': {'name': {'count': 0}, 'job': 'Dev'}}

CodePudding user response:

In fact in your D dictionary the emp1, emp2 and emp3 all point to the same reference (a same object in memory). That's the reason why, when you modify one of your inner dicts, you see the others as modified (in reality this is always the same and unique dict). You have to make copies of the initial test_dict.

from copy import deepcopy

D = {'emp1': {'name': deepcopy(test_dict), 'job': 'Mgr'},
     'emp2': {'name': deepcopy(test_dict), 'job': 'Dev'},
     'emp3': {'name': deepcopy(test_dict), 'job': 'Dev'}}

CodePudding user response:

This happen because each emp keys share the same dictionary object (same id). You must make a copy of it for each emp just using copy()

test_dict = {'count': 0}


D = {'emp1': {'name': test_dict.copy(), 'job': 'Mgr'},
     'emp2': {'name': test_dict.copy(), 'job': 'Dev'},
     'emp3': {'name': test_dict.copy(), 'job': 'Dev'}}

D['emp1']['name']['count']  = 1

print(D)

Output:

{'emp1': {'name': {'count': 1}, 'job': 'Mgr'}, 'emp2': {'name': {'count': 0}, 'job': 'Dev'}, 'emp3': {'name': {'count': 0}, 'job': 'Dev'}}
  • Related