本文介绍了Python dict.fromkeys返回相同的id元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我在python上执行此操作时,我会一次更新所有密钥.
When i do this on python i update all keys in one time.
>>> base = {}
>>> keys = ['a', 'b', 'c']
>>> base.update(dict.fromkeys(keys, {}))
>>> base.get('a')['d'] = {}
>>> base
{'a': {'d': {}}, 'c': {'d': {}}, 'b': {'d': {}}}
>>> map(id, base.values())
[140536040273352, 140536040273352, 140536040273352]
如果我使用[]
运算符而不是.get
,则不会发生这种情况:
If instead of .get
i use []
operator this not happen:
>>> base['a']['d'] = {}
>>> base
{'a': {'d': {}}, 'c': {}, 'b': {}}
为什么?
推荐答案
当您将新键的值初始化为{}
时,将创建一个新的词典,并且对该词典的引用正在成为这些值.只有一本字典,因此,如果您更改一本字典,则将更改全部".
When you initialize the value for the new keys as {}
a new dictionary is created and a reference to this dictionary is becoming the values. There is only one dictionary and so if you change one, you will change "all".
这篇关于Python dict.fromkeys返回相同的id元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!