【Python】Python - 存取Dictionary items。Python Access Dictionary Items.
【Python】Python - 存取Dictionary items。Python Access Dictionary Items.
存取 Items
你可以使用中括弧內的key name來存取dictionary。
範例
取得key="model"的值:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
上面輸出:Mustang
而 get()
這個method也會有相同的結果:
範例
Get the value of the "model" key:
x = thisdict.get("model")
上面輸出:Mustang
Get Keys
keys()
method 將會回傳dictionary內所有的keys的列表。
範例
取得keys的列表:
x = thisdict.keys()
上面輸出:dict_keys(['brand', 'model', 'year'])
keys的列表為dictionary的view,表示如果dictionary被修改了將會影響keys的列表:
範例
新增一個新的item到原始的dictionary,並看keys 列表被更新了:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.keys()
print(x) #before the change
car["color"] = "white"
print(x) #after the change
上面輸出:
dict_keys(['brand', 'model', 'year'])dict_keys(['brand', 'model', 'year', 'color'])
取得 Values
values()
方法將會回傳dictionary裡面的values的列表。
範例
取得values的列表:
x = thisdict.values()
dict_values(['Ford', 'Mustang', 1964])
values的列表為dictionary的view,表示任何改變發生都會反應在values的列表。
範例
對原始dictionary作修改,並看values的列表也會被更新:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x) #before the change
car["year"] = 2020
print(x) #after the change
dict_values(['Ford', 'Mustang', 1964])dict_values(['Ford', 'Mustang', 2020])
範例
新增一個新的item到原始的dictionary,並看values的列表也會被更新:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x) #before the change
car["color"] = "red"
print(x) #after the change
上面輸出:
dict_values(['Ford', 'Mustang', 1964])dict_values(['Ford', 'Mustang', 1964, 'red'])
取得 Items
items()
方法會回傳dictionary內的每個item,與tuples與list都相同。
範例
取得所有成對的key:values的列表:
x = thisdict.items()
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
回傳的列表為view,表示任何改變發生都會反應在values的列表。
範例
對原始的dictionary作修改,並看items列表同步被更新:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
print(x) #before the change
car["year"] = 2020
print(x) #after the change
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 2020)])
範例
新增一個新的item到原始dictionary,並看items列表同步被更新:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
print(x) #before the change
car["color"] = "red"
print(x) #after the change
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964), ('color', 'red')])
檢查Key 是否存在
使用
To determine if a specified key is present in a dictionary use the in
這個keyword去檢查key是否存在dictionary中:
範例
檢查是否"model" 在dictionary中存在:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
上面輸出:Yes, 'model' is one of the keys in the thisdict dictionary
留言
張貼留言