簡體   English   中英

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}}

而不是我想要/期望的:

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}}

我不確定這是否是深層/淺層復制問題或其他問題。

fromkeys為每個鍵使用相同的默認值。 如果您想要單獨的值,則可以使用dict理解並使用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}}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM