Mosa Abbas
Mosa Abbas

Reputation: 149

how to edit a dictionary value in python that have a dictionary as a value?

I'm trying to make a dictionary in python that has a key and a dictionary as a value like that

a = ('emp1','emp2')
b = ({'dep':'', 'sal':''})
comp = dict.fromkeys(a,b)
print(comp)
comp['emp1']['dep'] = 'IT'
comp['emp1']['sal'] = '300$'
print(comp)

and the output is like that

{'emp1': {'dep': '', 'sal': ''}, 'emp2': {'dep': '', 'sal': ''}}
{'emp1': {'dep': 'IT', 'sal': '300$'}, 'emp2': {'dep': 'IT', 'sal': '300$'}}

why all the values are changing if I'm trying to chang the value only for "emp1" can any one help ???

Upvotes: 1

Views: 72

Answers (2)

cs16
cs16

Reputation: 66

That is because the comp['emp1] and comp['emp2] actually refer to the same object.
You can verify it by id() function which returns the unique identifier of the python object

a = ('emp1', 'emp2')
b = ({'dep': '', 'sal': ''})
comp = dict.fromkeys(a, b)
print(id(comp["emp1"]))
print(id(comp["emp2"]))
print(comp)
comp['emp1']['dep'] = 'IT'
comp['emp1']['sal'] = '300$'
print(comp)

it returns

4467496912
4467496912
{'emp1': {'dep': '', 'sal': ''}, 'emp2': {'dep': '', 'sal': ''}}
{'emp1': {'dep': 'IT', 'sal': '300$'}, 'emp2': {'dep': 'IT', 'sal': '300$'}}

If u have to use fromkeys, The solution is

from copy import deepcopy
a = ('emp1', 'emp2')
b = ({'dep': '', 'sal': ''})
comp = dict.fromkeys(a, b)
comp = {key: deepcopy(b) for key in comp}
print(id(comp["emp1"]))
print(id(comp["emp2"]))
print(comp)
comp['emp1']['dep'] = 'IT'
comp['emp1']['sal'] = '300$'
print(comp)

the output will be what u want

4300371360
4301322592
{'emp1': {'dep': '', 'sal': ''}, 'emp2': {'dep': '', 'sal': ''}}
{'emp1': {'dep': 'IT', 'sal': '300$'}, 'emp2': {'dep': '', 'sal': ''}}

Upvotes: 1

Keyur Potdar
Keyur Potdar

Reputation: 7238

From the documentation:

fromkeys() is a class method that returns a new dictionary. value defaults to None. All of the values refer to just a single instance, so it generally doesn’t make sense for value to be a mutable object such as an empty list. To get distinct values, use a dict comprehension instead.

So, both the keys point to the same dictionary that you are trying to change.

You can use this instead:

comp = {key: {'dep': '', 'sal': ''} for key in ('emp1', 'emp2')}

Upvotes: 0

Related Questions