## Python基本語法 - 3
#### **Gino**
---
## dict
### **用Python寫字典**
---

dict:顧名思義就是字典
可以像字典一樣
快速查詢某個「單字」對應到的「解釋」
----
單字:key
對應到想要查的解釋:value

----
## dict的性質
----
1. 不會有兩個相同的key存在
2. key 可以是各種型態的資料
(除了list, set, dict以外,還有可以被修改的東西都不行)
---
### dict
- **- 建立 -**
- 修改
- 檢查&查詢
- 遍歷
----
```python=
# 有初始資料的dict
menu = {"Apple": 20, "Banana": 10, "Cucumber": 25}
menu = dict(Apple=20, Banana=10, Cucumber=25)
# 空的dict
menu = {}
menu = dict()
# for迴圈建立dict
fruit = ["Apple", "Banana", "Cucumber"]
price = [20, 10, 25]
menu = {fruit[i]: price[i] for i in range(0, 3)}
```
---
### dict
- 建立
- **- 修改 -**
- 檢查&查詢
- 遍歷
----
```python=
menu["Apple"] = 30
```
直接修改key對應到的value
----
```python=
del menu["Banana"]
menu.pop("Banana")
```
刪除某個key
----
```python=
print(menu.pop("Banana")) # 10
```
pop操作還會回傳value
(刪除"Banana",回傳"Banana"對應的價格 $\rightarrow$ 10)
----
做刪除操作時
字典裡面沒有那個key的話程式就會出錯
最好先檢查有沒有那個key
```python=
if "Apple" in menu:
menu.pop("Apple")
```
---
### dict
- 建立
- 修改
- **- 檢查&查詢 -**
- 遍歷
----
```python=
print(menu["Cucumber"]) # 25
```
查詢:dict[key]
----
```python=
if "Apple" in menu:
...
if "Apple" in menu.keys():
...
```
查詢key有沒有在dict裡面
----
```python=
if 25 in menu.values():
...
```
查詢value有沒有在dict裡面
---
### dict
- 建立
- 修改
- 檢查&查詢
- **- 遍歷 -**
----
```python=
menu = {"Apple": 20, "Banana": 10, "Cucumber": 25}
for fruit in menu:
print(fruit, menu[fruit])
# "Apple" 20
# "Banana" 10
# "Cucumber" 25
```
for迴圈
取出來的資料有固定順序
----
```python=
# 遍歷所有key
for fruit in menu.keys():
...
for fruit in menu:
...
# 便利所有value
for price in menu.values():
...
```
----
```python=
for item in menu.items():
print(item)
# ("Apple", 20)
# ("Banana", 10)
# ("Cucumber", 25)
```
items()會把key, value綁在一起變成一個tuple
{"metaMigratedAt":"2023-06-15T23:21:52.681Z","metaMigratedFrom":"YAML","title":"Python基本語法 - 3","breaks":true,"slideOptions":"{\"transition\":\"fade\",\"spotlight\":{\"enabled\":false}}","contributors":"[{\"id\":\"ac1507e0-f05c-4708-bdd2-c56d13fb0dbb\",\"add\":7109,\"del\":5144}]"}