如何在以字典为值的python中编辑字典值? [英] how to edit a dictionary value in python that have a dictionary as a value?

查看:60
本文介绍了如何在以字典为值的python中编辑字典值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用python制作一个字典,该字典具有一个键和一个像这样的值的字典

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)

输出就是这样

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

如果我仅尝试为 "emp1" 更改 ,为什么所有值都在更改 谁能帮忙???

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

推荐答案

来自

fromkeys()是返回新字典的类方法. value 默认为 None .所有的值都只引用一个实例,因此 value 成为可变对象(例如空列表)通常是没有意义的.要获取不同的值,请改用dict理解.

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.

您可以改用它:

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

这篇关于如何在以字典为值的python中编辑字典值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆