0
我有以下变量:Python字典值更新
list_m = ["a","b","c"]
list_s = ['x','y','z']
dict_m = dict.fromkeys(list_m[:])
dict_s = dict.fromkeys(list_s[:],copy.deepcopy(dict_m)) # empty dict of dicts
所以我
In[22]: dict_s
Out[22]:
{'x': {'a': None, 'b': None, 'c': None},
'y': {'a': None, 'b': None, 'c': None},
'z': {'a': None, 'b': None, 'c': None}}
在更新dict_s值这样
dict_s['x']['a']= np.arange(10)
我得到
In[27]: dict_s
Out[27]:
{'x': {'a': array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), 'b': None, 'c': None},
'y': {'a': array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), 'b': None, 'c': None},
'z': {'a': array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), 'b': None, 'c': None}}
什么,而不是我想要的/预期:
In[27]: dict_s
Out[27]:
{'x': {'a': array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), 'b': None, 'c': None},
'y': {'a': None, 'b': None, 'c': None},
'z': {'a': None, 'b': None, 'c': None}}
我完全不明白,如果这是一个深/浅拷贝的问题还是其他什么东西。
请解释为什么你想使用此代码做。 – Soviut
我想要以后的结果而不是前者 – dayum
您的deepcopy只执行一次,然后将此副本分配给所有三个键。尝试一个字典理解,而不是fromkeys –