0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

辞書のキーに変数を使う方法 mshmura

Posted at

元々の辞書

test.py
dic = {"りんご":200,"みかん":200,"なし":100}

通常、変数を使用して辞書を作ろうとするとエラーになります...と思ったらエラーになりませんでした。以前はエラーになっていたはずなのに変わったのかな...

new_key = "メロン"
dic[new_key] = 700
print(dic)

出力結果

{'りんご': 200, 'みかん': 200, 'なし': 100, 'メロン': 700}

下記コードを使おうと思っていたのですが、不要でしたね。

new_key = "メロン"
v = 700
exec('dic["{}"] = {}'.format(new_key, v))
print(dic)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?