私は次のように辞書を作成しました:
gP = dict.fromkeys(range(6), {'a': None, 'b': None, 'c': None, 'd': None})
さて、値を変更しようとすると、次のようになります。
gP[0]['a'] = 1
何らかの理由で、a
(それらが属するキーに関係なく)のすべての値が以下に示すように1に変更されます。
{0: {'a': 1, 'b': None, 'c': None, 'd': None},
1: {'a': 1, 'b': None, 'c': None, 'd': None},
2: {'a': 1, 'b': None, 'c': None, 'd': None},
3: {'a': 1, 'b': None, 'c': None, 'd': None},
4: {'a': 1, 'b': None, 'c': None, 'd': None},
5: {'a': 1, 'b': None, 'c': None, 'd': None}}
私が間違っていることは何ですか?適切な割り当てステートメントは何ですか?
@decezeが言ったように、Pythonはコピーを作成しません。キーと値のペアのすべての値の部分で同じdictを参照しています。
別の方法は次のとおりです。
gP = {x: {'a': None, 'b': None, 'c': None, 'd': None} for x in range(6)}
更新:@Chris_Randsによるこの回答のはるかにクリーンなバージョンがあります:
{x: dict.fromkeys('abcd') for x in range(6)}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加