pythonの辞書から値を取得する場合には、fruits[“apple”]のようにキーを指定しますが、下のように存在しないキーを指定するとエラーになります。
C#
fruits = {
"apple": 5.3,
"banana": 1.9,
"orange": 3.4,
"grape": 3.9
}
print(fruits["apple"])
# 5.3
print(fruits["mango"])
# keyerror
dict.get()メソッド
dictのget( )メソッドで値を取得すると、存在しないキーを指定してもエラーにならず、デフォルトの値を指定することもできます。
C#
print(fruits.get("banana"))
# 5.3
print(fruits.get("mango", 0))
# 0
dictのget()の使いどころとして、コマンドの振り分け(ディスパッチ)の用途で使うことができます。
C#
def start():
print("起動します")
def stop():
print("停止します")
def standby():
print("待機します")
transitions = {
"power_on": start,
"power_off": stop,
"idle": standby,
}
command = "power_on"
action = transitions.get((command), lambda: print("不明な状態遷移"))
action()
command = "shut_down"
action = transitions.get((command), lambda: print("不明な状態遷移"))
action()
この例では辞書 transitions をコマンドによってアクションを選択できるように使っています。定義していないコマンドを指定した場合はエラーにならず、既定のアクションを実行するわけです。
すべてのキーと値を取り出す
C#
my_dict = {'name': 'Alice', 'age': 25, 'city': 'Tokyo'}
for key in my_dict.keys():
print(f"{key} ", end='')
print()
# name age city
全ての値を取り出す
C#
for value in my_dict.values():
print(f"{value} ", end='')
print()
すべてのキーと値を取り出す
C#
for key, value in my_dict.items():
print(f"{key}: {value} ", end='')
# name: Alice age: 25 city: Tokyo
コメント