辞書の基礎
入門Python3 3.4
任意のキーをインデックスとして指定できるリストみたいなかんじですね。
空辞書の作成
hash = {} print(hash)
$ py main.py {}
辞書の作成
hash = { "foo": 1, "bar": 2, "baz": 3 } print(hash["foo"])
$ py main.py 1
任意のキーには文字列以外にもイミュータブルな値なら何でも指定できる、つまりタプルですら指定できるということになります。実験してみます。
key1 = "foo","bar","baz" key2 = "foo","bar", hash = { key1: "key1!", key2: "key2!", } print(hash[key1]) print(hash["foo","bar"])
$ py main.py key1! key2!
updateによる辞書のマージ
updateを使って辞書同士のマージができる。もしキーが重複していた場合はupdateの引数に渡した方の辞書が優先される
hash1 = { "foo": 1, "bar": 2, } hash2 = { "bar": 3, # barが重複 "baz": 4, } hash1.update(hash2) print(hash1)
$ py main.py {'foo': 1, 'bar': 3, 'baz': 4}
inによるキーの存在チェック
inを使えば指定のキーが存在しているかどうかチェックすることができる
hash = { "foo": 1, "bar": 2, } result = "foo" in hash print(result) result = "baz" in hash print(result)
$ py main.py True False
getによる要素の取得
通常、要素を取得するには[]演算子で取得できるが、存在しないキーの場合は例外となる。
hash = { "foo": 1, "bar": 2, } print(hash["baz"]) # 存在しないキー
$ py main.py Traceback (most recent call last): File "main.py", line 7, in <module> print(hash["baz"]) KeyError: 'baz'
こういった場合あらかじめinで存在チェックして処理してもいいが、getを使うことでも代用できる。
hash = { "foo": 1, "bar": 2, } print(hash.get("baz")) # 存在しないキー
$ py main.py None
といったように例外にならずnullオブジェクトが返ってくるようになります。
またgetの第二引数にキーが存在しない場合のデフォルト値を設定することもできます。
hash = { "foo": 1, "bar": 2, } print(hash.get("baz",3)) # bazが無い場合に3を返す
$ py main.py 3