python 字典值更新
python dictionary value update
我有以下变量:
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}}
而不是我 wanted/expected:
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}}
我不太明白这是 deep/shallow 复制问题还是其他问题。
fromkeys
对每个键使用相同的默认值。如果你想要单独的值,你可以使用字典理解并为每个值生成新的字典 fromkeys
:
>>> 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}}
我有以下变量:
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}}
而不是我 wanted/expected:
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}}
我不太明白这是 deep/shallow 复制问题还是其他问题。
fromkeys
对每个键使用相同的默认值。如果你想要单独的值,你可以使用字典理解并为每个值生成新的字典 fromkeys
:
>>> 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}}