Created
March 24, 2014 20:45
-
-
Save dogrunjp/9748789 to your computer and use it in GitHub Desktop.
Pythonのリストにdict型の変数をappendすると変数がポインタ的に振る舞うので…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
リストに複数のdictをappendしようとすると下のように書いた場合、追加したすべてのdict型の変数が同じ値になる。 | |
mylist = [] | |
mydict = {} | |
for i,v in enumerate(items): | |
mydict['name'] = v | |
mydict['value'] = i | |
mylist.append(mydict) | |
この場合dict.copy()を使うと適切な結果になる。 | |
for i, v enumerate(items): | |
mydict['name'] = v | |
mydict['value'] = i | |
mylist.append(mydict.copy()) |
私も同様に問題にぶつかっており、解決できました。
ありがとうございます。
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
独学初学者です。この問題に悩まされていたのですが、こちらの方法で解決できました。ありがとうございます!