問題
Python辞書からインターフェース名を取得する。空欄に入るコードはどれか。
json_object = {
"type": "network",
"if-name": "eth0",
"description": "ethernet",
"ip-address": "170.15.15.11",
"subnet-mask": "255.255.255.0",
"nat-direction": ""
}
# 空欄
print(interface_name)
- A
interface_name = json_object["if-name"] - B
interface_name = json_object[0] - C
interface_name = json_object["eth0"] - D
interface_name = json_object[0][2]
正解:A
理由
辞書はキーを指定して値を取得する。 この例のインターフェース名は、if-nameに対応するeth0である。
選択肢ごとの説明
- A.
interface_name = json_object["if-name"] キー
if-nameに対応する値eth0を取得する。- B.
interface_name = json_object[0] 整数のキー
0がないため、KeyErrorが発生する。辞書の添字にはキーを指定する。- C.
interface_name = json_object["eth0"] eth0はif-nameの値である。キーとして参照するとKeyErrorになる。- D.
interface_name = json_object[0][2] 最初の
json_object[0]でKeyErrorになるため、続く[2]の処理へ進めない。