2017-02-28 14 views
0

私は、次の変数があります。だから私はこのPythonの辞書値更新

dict_s['x']['a']= np.arange(10) 

ようdict_sの値を更新するには

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

を持って

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

これは深い/浅いコピー問題や何か他のものであるならば、私は正確に理解していません。

+0

あなたは、このコードで何をしようとしている理由を説明してください。 – Soviut

+0

私は後の結果を望んでいますが、前者はありません – dayum

+1

ディープコピーは一度だけ実行され、このコピーは3つのキーすべてに割り当てられます。 fromkeysの代わりにdictの理解を試してください –

答えて

3

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