6
5

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 5 years have passed since last update.

Pythonで<br>dictのキーに<br>文字列以外を使う

Posted at
1 / 10

dictのキーには文字列をよく使うけど...

stock = {
    "orange": 3,
    "apple": 1,
}

実は文字列以外も使える

d = {
    1: "数値",
    date(2016, 1, 1): "日付"
    (1, 2): "タプル",
    None: "None"
}

キーの仕様

  • ハッシュ可能でイミュータブルなオブジェクトならなんでも使える
  • 1つのdictに複数の型が混在していてもOK
  • NoneでもOK

キーに使える型の例

  • str
  • int
  • date
  • Enum
  • tuple
  • 関数

実践例


実践例

  • タプルで複合キー
  • リストの代わりに数値キーのdictを使う

タプルで複合キー

stock = {
    ("東京支店", "orange"): 3,
    ("東京支店", "apple"): 1,
    ("名古屋支店", "orange"): 8,
}
stock["名古屋支店", "apple"] = 4

リストの代わりに数値キーのdictを使う

  • キーに欠落があっても大丈夫
a = {
    1: "apple",
    3: "orange",
}

リストの代わりに数値キーのdictを使う

  • defaultdictと組み合わせれば効果的
from collections import defaultdict
a = defaultdict(str)
a[1] = "apple"
a[3] = "orange"
l = max(l.keys())
for i in range(0, l + 1):
    print("%d: %s" % (i, a[i]))
0: 
1: apple
2: 
3: orange
6
5
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
6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?