# Dictionary 繼續在資料結構的世界裡,把一堆各式 type 的資料裝在一起的方式,除了 list 和 string, tuple 以外,還可以用 dictionary Dictionary 跟上述三種不同的地方在於,那三種都是把資料用水平一串(一條?)的概念來呈現,像是 index 也本身就是排排站的意味,但 dictionary 是索引的概念 Dictionary 是 Python 內建的特殊資料結構,(在其他語言可能要用其他方式或自己寫才能達到相同的效果),所有東西都是一對一對的,像字典一樣,每一個詞都有一個解釋,這個詞概念的東西稱為 key ,而配對到的解釋稱為 value 長這樣 ``` python mydict = {"twelve":12, "six":6, "twenty":20} ``` 其中 `"twelve"`, `"six"`, 和 `"twenty"` 都是 key,type 是 string 的 key `12`, `6`, 和 `20` 是 value,type 是 int 的 value 每一個 key 都配對到一個 value,key 不能重複,但 value 可以 要拿到一個 dictionary 裡面的值,不是像 list 一樣用 index by index 地查找,而是透過 key 來 directly access,像是 ``` python mydict = {"twelve":12, "six":6, "twenty":20} print(mydict["six"]) ``` 如果 six 這個 key 不存在,就會獲得 `KeyError` 為了避免程式執行時出現不必要的 error 讓整個程式中斷,一個安全的 access dictionary 方式是透過 `dictionary.get()` 這個 function,如果 `.get()` 括號內的 key 存在,這個 function 就會回傳該 key 的 value,如果不存在,則回傳 None 試試: ``` python mydict = {"twelve":12, "six":6, "twenty":20} print(mydict.get("sixx")) ``` 另一個 `.get()` 的酷用法是可以指定如果 key 不存在要回傳什麼,試試: ``` python mydict = {"twelve":12, "six":6, "twenty":20} print(mydict.get("sixx", "sad no key")) ``` <br></br> 當然 dictionary 的創建不需要在一開始就指定好,也可以跟 list 的 `.append()` 一樣慢慢擴增,試試: ``` python mydict = {"twelve":12, "six":6, "twenty":20} print(mydict) mydict["one"] = 1 print(mydict) ``` --- 另外,像所有其他資料結構一樣,dictionary 也可以用 loop 去 access,想想會印出什麼然後試試: ``` python mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9] for i in mylist: print(i) #------------------------------------- mydict = {"twelve":12, "six":6, "twenty":20} for i in mydict: print(i) for i in mydict: print(mydict[i]) ``` 更進階的可以試試: ``` python mydict = {"twelve":12, "six":6, "twenty":20} for i in mydict.items(): print(i) for i, j in mydict.items(): print(j, i) ``` 這樣就可以看出許多 dictionary 的特質囉 <br></br> :::spoiler 小練習 with Turtle 來用 turtle 畫折線圖吧,先做一個 dictionary,讓 key 是 x 座標,value 是 y 座標,再讓烏龜畫出來吧 ::: <br></br> :::spoiler 來寫個小複雜的東西吧 字典是個好東西,特別是翻譯的時候,現在已知有兩個 list -- 英文與西班牙文的單字列表,並且已知這兩個 list 的單字順序是一樣的,如下 ``` python eng_list = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"] spa_list = ["uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", "diez"] arab_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` 目標是知道這兩個語言,對於一樣意思的單字,字母數是否一樣,最後得到哪一個語言背單字比較容易的結論,所以要怎麼做到呢 ::: --- :::spoiler Additional readings https://runestone.academy/ns/books/published/thinkcspy/Dictionaries/toctree.html ::: <br></br> :::info [BACK](https://hackmd.io/@lhsueh1/python101) :::