Why dictionary? 難道list不夠嗎?
想像一下我們要查詢每個國家的首都。根據我們之前學到的 list
,可以使用以下方法:
首先建立兩個 list
,第一個為國家名、第二個為首都名:
countries = ["spain", "france", "germany", "iceland"]
capitals = ["madrid", "paris", "berlin", "reykjavik"]
若要查詢法國(France)的首都,先用 index
查詢france在country的位置,再依此為媒介在capitals中搜尋:
# define ind_ger as index of "france"
ind_ger = countries.index("france")# use ind_ger to print out the capital of France
print(capitals[ind_ger])
然而這並不是一個有效率的方法。全世界有兩百多個國家,難道我們要為每個國家建立一個index變數以查詢他們的首都?
因此,我們可以使用 dictionary
來改善效率,注意dictionary的開頭結尾以 {}
來表示:
#建立europe
europe = { "spain":"madrid", "france":"Paris", "germany":"berlin", "iceland":"reykjavik"}
dictionary中的第一位為索引,稱為 keys
,類似我們一般查字典時使用的注音符號/ 部首。
可以使用 .keys
來查詢此字典中的所有索引。
另外,如同使用index順序查詢list一樣,使用key就可以簡單找到dictionary中已經定義好的首都名字。
print(europe.keys())
#結果將是:dict_key['spain', 'france', 'germany', 'iceland']print(europe["germany"])
#結果將是:berlin
keys
有以下幾個特性,需注意:
- Unique 獨一無二:一個
dictionary
裡面的keys
不能重複。若建立dictionary
的時候有重複的keys
,Python只會認得最新的那個(最後輸入的那個)。 - Immutable 永恆不變:想像一下你的字典,部首總不會每年變動吧?same as dictionary in Python.
keys
可以是strings/ booleans/ integers/ floats,但不可以是list。
如何調整dictionary的內容?
試著把荷蘭(Netherland)的首都(Amsterdam) 加入 europe
中:
europe["netherland"]="amsterdam"print(europe)
europe = { "spain":"madrid", "france":"Paris", "germany":"berlin", "iceland":"reykjavik", "netherland"="amsterdam"}
可以用以下程式碼確認使否有加入成功:
"netherland" in europe
# python若回覆True, 代表europe裡面確實有netherland這個keys
更改內容,假設荷蘭的首都今天突然變成鹿特丹 (?!):
europe["netherland"] = "rotterdam"print(europe)
europe = { "spain":"madrid", "france":"Paris", "germany":"berlin", "iceland":"reykjavik", "netherland"="rotterdam"}
仔細觀察程式碼可以發現,增加 和 修改的命令是相同的!
回想一下前面提到的 keys
定義的第二條(Immutable 永恆不變),有了這個前提,python不會也不能幫你新增一個keys同樣叫做netherland,而是幫你更新了資料。
刪除資料,想像今天荷蘭突然退出歐盟(?!):
del(europe["netherland"])print(europe)
europe = { "spain":"madrid", "france":"Paris", "germany":"berlin", "iceland":"reykjavik"}
前面提到, list
不能作為 dictionary
的 keys
,但list
是可以作為後面dictionary pair 中後者的資料:
# 更新europe資料如下:europe = { 'spain': { 'capital':'madrid', 'population':46.77 },'france': { 'capital':'paris', 'population':66.03 },'germany': { 'capital':'berlin', 'population':80.62 },'norway': { 'capital':'oslo', 'population':5.084 } }print(europe["france"])#結果會是:{'capital': 'paris', 'population': 66.03}
假設我們要把冰島的資訊放進去:
# Create sub-dictionary data
data = {'capital':'reykjavik','population':0.35}# Add data to europe under key 'iceland'
europe['iceland']=dataprint(europe)
# 結果會是:europe = { 'spain': { 'capital':'madrid', 'population':46.77 },'france': { 'capital':'paris', 'population':66.03 },'germany': { 'capital':'berlin', 'population':80.62 },'norway': { 'capital':'oslo', 'population':5.084 },'iceland': { 'capital':'reykjavik','population':0.35 }
dictionary與list的差別?
兩個最大的差異就是索引方式:
list
使用順序(order)作為索引,而 dictionary
使用keys作為索引。
若你要使用的資料可以清楚的用順序辨別、或者你需要選取某一個區間的資料,那你適合使用list
。
反之,若你的資料需要用關鍵字來搜尋比較有效率,你應該使用 dictionary
來儲存他們。