[英]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我正在尝试在 python 中制作一个字典,它有一个键和一个字典作为这样的值
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 ???为什么如果我试图昌值仅适用于所有的观念正在转变"emp1"
任何一个可以帮助???
That is because the comp['emp1] and comp['emp2] actually refer to the same object.那是因为 comp['emp1] 和 comp['emp2] 实际上指的是同一个对象。
You can verify it by id() function which returns the unique identifier of the python object您可以通过 id() 函数验证它,该函数返回 python 对象的唯一标识符
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如果你必须使用 fromkeys,解决方案是
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': ''}}
From the documentation :从 文档:
fromkeys()
is a class method that returns a new dictionary.fromkeys()
是一个返回新字典的类方法。 value defaults toNone
.值默认为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')}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.