Skip to content

Instantly share code, notes, and snippets.

@dogrunjp
Created March 24, 2014 20:45
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dogrunjp/9748789 to your computer and use it in GitHub Desktop.
Save dogrunjp/9748789 to your computer and use it in GitHub Desktop.
Pythonのリストにdict型の変数をappendすると変数がポインタ的に振る舞うので…
リストに複数の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())
@saitoy4950
Copy link

独学初学者です。この問題に悩まされていたのですが、こちらの方法で解決できました。ありがとうございます!

@manabian-
Copy link

私も同様に問題にぶつかっており、解決できました。

ありがとうございます。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment