将值设置为字典的字典值 [英] Setting a value to a dictionary's dictionary value
问题描述
代码:
>>> mydict = {}
>>> keylist = ['a','b','c']
>>> mydict=dict.fromkeys(keylist,{})
>>> mydict['a']['sample'] = 1
>>> mydict
{'a': {'sample': 1}, 'c': {'sample': 1}, 'b': {'sample': 1}}
我期待着 mydict ['a'] ['sample'] = 1
将这个值设置为一个字典值,并得到这个: {'a':{'sample':1},'c':{},'b':{}}
。
I was expecting mydict['a']['sample'] = 1
would set the value just for a's dictionary value and would get this: {'a': {'sample': 1}, 'c': {}, 'b': {}}
.
我在这里缺少什么?
推荐答案
问题是你添加了相同的
mydict = dict((key, {}) for key in keylist)
在上述代码中,您将创建一个新的字典与每个键配对。在您的原始代码中,函数fromkeys接受了参数(您提供的空字典),并添加了这个确切的参数 - 您创建的单个空字典传递给函数 - 到每个键。当那个字典被改变的时候,那个变化就到处都是。
In the above code, you create a new dictionary to pair with each key. In your original code, the function fromkeys took the argument (the empty dictionary you provided) and added that exact argument - that single empty dictionary you created to pass in to the function - to each of the keys. When that one dictionary was changed, then, that change showed up everywhere.
这篇关于将值设置为字典的字典值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!