python字典值更新

python字典值更新,python,dictionary,pass-by-reference,deep-copy,Python,Dictionary,Pass By Reference,Deep Copy,我有以下变量: 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':

我有以下变量:

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}}
我不太明白这是深层次/浅层复制问题还是其他问题

对每个键使用相同的默认值。如果需要单独的值,可以使用dict CONTRUSION并使用
fromkeys
为每个值生成新的dict:

>>> list_m = ["a","b","c"]
>>> list_s = ['x','y','z']
>>> dict_s = {x: dict.fromkeys(list_m) for x in list_s}
>>> dict_s
{'y': {'a': None, 'c': None, 'b': None}, 'x': {'a': None, 'c': None, 'b': None}, 'z': {'a': None, 'c': None, 'b': None}}
>>> dict_s['y']['a'] = 100
>>> dict_s
{'y': {'a': 100, 'c': None, 'b': None}, 'x': {'a': None, 'c': None, 'b': None}, 'z': {'a': None, 'c': None, 'b': None}}
对每个键使用相同的默认值。如果需要单独的值,可以使用dict CONTRUSION并使用
fromkeys
为每个值生成新的dict:

>>> list_m = ["a","b","c"]
>>> list_s = ['x','y','z']
>>> dict_s = {x: dict.fromkeys(list_m) for x in list_s}
>>> dict_s
{'y': {'a': None, 'c': None, 'b': None}, 'x': {'a': None, 'c': None, 'b': None}, 'z': {'a': None, 'c': None, 'b': None}}
>>> dict_s['y']['a'] = 100
>>> dict_s
{'y': {'a': 100, 'c': None, 'b': None}, 'x': {'a': None, 'c': None, 'b': None}, 'z': {'a': None, 'c': None, 'b': None}}

请解释您试图使用此代码的原因。我想要稍后的结果,而不是表单。您的deepcopy只执行一次,然后将此副本分配给所有三个键。试着用dict理解而不是fromkeys
dict_s={k:dict.fromkeys(list_m)表示list_s}
请解释为什么要使用此代码。我想要的是后面的结果,而不是之前的结果。您的深度复制只执行一次,然后将此复制分配给所有三个键。尝试对列表中的k进行dict理解,而不是fromkeys
dict\u s={k:dict.fromkeys(list\u m)