---
###### tags: `資訊之芽`
---
# Dictionary
![](https://i.imgur.com/rPf3fx5.png =30%x)
src: chainsaw man
資芽北區2023 講師YuKai 洪郁凱
----
# Outline
- Before Dict
- What is Dict
- How do Dict works
- Usage
- Some Combo Skills
---
# Before Dict
你應該要知道:
- 利用學過的資料型別存資料
- 如何存取List/Tuple的元素
---
# What is Dict
Dictionary 字典
用大括號來宣告
```python=
ex_dict = {"bday": 928, "name": "Kain"} #這裡以字串:數字為例
print(ex_dict)
```
----
# What is Dict
用其他的方式來宣告
```python=
ex_dict = dict([["bday", 928], ["name", "Kain"]]) #傳入一個List/Tuple
# 每個元素為一個鍵值對 可用List/Tuple
```
----
# What is Dict
Dictionary 字典
用大括號來宣告
最大的特色是可以用數字之外的物件來取值
```python=
ex_dict = {"bday": 928} #這裡以字串為例
ex_list = [928]
print(ex_list["bday"], ex_list[0])
```
<!-- .element: class="wrap-code" -->
Key-Value Pairs 鍵值對
----
# What is Dict
|Key-Value|Index|
|---|---|
|一月 -> Jan |0 -> Jan|
|二月 -> Feb |1 -> Feb|
|九月 -> Sep |8 -> Sep|
```python=
mon_list = ["Jan", "Feb", "Mar", ..., "Sep"]
mon_dict = {"一月": "Jan", "二月": "Feb", "三月": "Mar", "九月": "Sep"}
print(mon_list[0], mon_dict["一月"])
```
<!-- .element: class="wrap-code" -->
----
# What is Dict
萬一資料不是有順序的呢?
```python=
location_dict = {"台北": "Taipei", "桃園": "Taoyuan"}
```
----
# What is Dict
```python=
ex_dict = {"Mutated": "變異的", "Crab": "螃蟹"}
print(ex_dict["Mutated"]) #一個長得很像字典的範例
print(ex_dict["變異的"]) # 不能反向!
print(ex_dict["Dior"]) # 不能找沒在字典裡面的
```
最後兩行會導致Key Error
都是因為字典內沒有對應Key導致
----
# Practice
用三種方式宣告一個字典
```python=
keys_list = ["名字", "屬性", "顏色"]
value_list = ["皮卡丘", "雷系", "顏色"]
```
----
# Practice
用三種方式宣告一個字典
```python=
keys_list = ["名字", "屬性", "顏色"]
value_list = ["皮卡丘", "雷系", "顏色"]
# Hints:
# 用大括號
# 用dict()及雙層list
# (bonus)
```
---
# How do Dict works
Key值可以不只是字串
```python=
ex_tuple = (9, 2, 8)
ex_dict = {ex_tuple: 928928} #用Tuple也可以
print(ex_dict[ex_tuple])
```
----
# How do Dict works
Dict 是用一個酷東西["Hash"](https://thepythoncorner.com/posts/2020-08-21-hash-tables-understanding-dictionaries/)來實作的
這裡是參考資料 不會講
----
# How do Dict works
Hashable:
String, Tuple, Numbers, Frozen Set, Lambda Function(?)
好玩的[參考資料](https://www.geeksforgeeks.org/why-and-how-are-python-functions-hashable/)
---
# Usage
新增,修改,刪除,迭代
----
# Usage
新增
```python=
info = {}
info["Kain"] = 928
print(info["Kain"])
```
----
# Usage
修改
```python=
info = {"Kain": 928}
info["Kain"] = "B09"
print(info["Kain"])
```
----
# Usage
刪除
```python=
info = {"Kain":928}
info.pop("Kain")
print("Kain" in info)
```
----
# Usage
刪除
```python=
info = {"Kain": 928}
del info["Kain"]
print("Kain" in info) # 確認 "Kain"-928 還在不在
```
----
# Usage
全部刪除!
```python=
info = {"Kain":928, ""}
info.clear()
```
----
# Usage
迭代
```python=
calories = {"apple":243, "banana":132, "candy":432}
for i in calories:
print(i)
```
for會迭代Key:Value裡面的Key
----
# Usage
迭代(Key)
```python=
calories = {"apple":243, "banana":132, "candy":432}
for i in calories.keys():
print(i)
```
----
# Usage
迭代(Value)
```python=
calories = {"apple":243, "banana":132, "candy":432}
for i in calories.values():
print(i)
```
----
# Usage
迭代(Key,Value)
```python=
calories = {"apple":243, "banana":132, "candy":432}
for i in calories.items():
print(i)
```
會將 (Key,Value) 組合成Tuple來迭代
----
# Usage
合併兩個字典
```python=
dict_a = {"學校": "CKHS", "年級": "10th"}
dict_b = {"類組": "三", "校排": "10%"}
dict_c = merge(dict_a,dict_b)??? #這是psudo-code 不要記
```
----
# Usage
合併兩個字典
用update
用*星*號*爆*開
```python=
dict_c = {**dict_a, **dict_b} # c為合併後的字典
dict_a.update(dict_b) # a為合併後的字典
#暴雷:之後可以用星號 *list_a / **dict_a 炸開並傳入func當作參數
```
---
# Combo Skills
處理Key Error
----
# Combo Skills
What is Key Error
```python=
student = {}
student["Kain"] = "B09"
print(student["Jolin"])
```
----
# Combo Skills
先檢查再取值
```python=
if "Jolin" in student:
print(student["Jolin"])
```
----
# Combo Skills
也可以用Method
![](https://i.imgur.com/RHxCAwc.png)
```python
print(student.get("Jolin"))
```
---
# Method 大全
![](https://i.imgur.com/3CORHq8.png)
```python=
help(dict) # 按q退出
```
----
# Quiz
1. 給定任意Dict 請輸出一個Key-Value對調的dict (要比下面的更好)
2. 給出一個Dict 把下面的版本弄壞
```python=
ans_dict = dict()
for k,v in given_dict.item():
ans_dict[v] = k
```
---
# Set
```python=
ex_tuple = (928,)
ex_list = [928,]
ex_dict = {"bday": 928}
ex_set = {928}
```
----
# Set
- unordered
- hashable elements only
- mutable
- frozenset for immutable usage
- NO duplicated elements
----
# Set
```python=
dict_a = {}
set_a = set(["Vokda","Rum","Gin","Orange Juice"])
set_a.add("Tequila")
set_a.remove("Orange Juice")
```
----
# Set
![](https://i.imgur.com/hmAVl54.png)
src : [learnbyexample](https://www.learnbyexample.org/python-set/)
----
# Set
Union
```python=
set_a = {1, 2, 3, 5, 8, 13}
set_b = {2, 3, 5, 7, 11, 13}
print(set_a.union(set_b))
print(set_a | set_b) # Elegant!
```
----
# Set
Intersection
```python=
set_a = {1, 2, 3, 5, 8, 13}
set_b = {2, 3, 5, 7, 11, 13}
print(set_a.intersection(set_b))
print(set_a & set_b) # Elegant!
```
----
# Set
Difference
```python=
set_a = {1, 2, 3, 5, 8, 13}
set_b = {2, 3, 5, 7, 11, 13}
print(set_a.difference(set_b))
print(set_a-set_b) # Elegant!
```
----
# Set
Symmetric Difference
```python=
set_a = {1, 2, 3, 5, 8, 13}
set_b = {2, 3, 5, 7, 11, 13}
print(set_a.symmetric_difference(set_b))
print(set_a^set_b) # Elegant!
```
----
# Set
![](https://i.imgur.com/9Zw9FSU.png)
src: Spy X Family
---
# Homework
[3035](https://neoj.sprout.tw/problem/3035)
[3036](https://neoj.sprout.tw/problem/3036)
---
# Hash
雜湊函式(Hash Function)
```
hash(obj, /)
Return the hash value for the given object.
Two objects that compare equal must also have the same hash value, but the
reverse is not necessarily true.
```
----
# Function
----
f(x) = 9 x + 28
f(100) = 928
f(3) = ?
f(?) = 73
----
定義妥善的f需要有
- 定義域/值域
- 好的演算法
e.g. $\sin(x), \tan(x)$
----
# Hash Function
好的Hash Function需要有
- hard to reverse
- easy to compute
- $x=y \leftrightarrow h(x) = h(y)$
- Given $h(x)$, hard to find $x$
e.g. SHA256 SHA512
----
# Hash Function
- 保護密碼
- 將定義域的東西壓進值域
- 誰是臥底(?)
----
# Hash Function
```python=
f(x) = x%17
g(x) = 2x + 3
```
----
# Hash Fucntion
```python=
f(x) = x裡字母a的數量
```
----
{"metaMigratedAt":"2023-06-17T20:51:18.144Z","metaMigratedFrom":"Content","title":"Dictionary","breaks":true,"contributors":"[{\"id\":\"9a14c697-53b2-4214-a12a-512e946e0176\",\"add\":6651,\"del\":440}]"}