# 6. 字典

## I. 什麼是字典(Dictionary)?

直接英翻中的話就稱為：字典\
因此，其實Dictionary就像大家小時候查字典的方式相同\
我們會利用部首 or 筆畫數 or 注音符號索引，找到我們想找的內容在哪一頁\
在Python中，我們也是利用索引值(**Key**)去找相對應的內容(**Value**)唷!!

![](https://i.imgur.com/BpVDnar.png)

## II. 字典有甚麼優勢

有沒有想過，其實儲存大量資料也可以利用陣列就好\
為什麼需要有「字典」這種資料型態呢?

## III. 創造一個字典

`<dict_name> = {<Key>：<Value>}`。 每一對`<Key>：<Value>`利用逗號分隔

```python
Lance_dict = {
  "name":"Lance",
  "age":18,
  "habbit":"eating"
}
```

直接利用`dict()`將它變為`dict`的型態

```python
Lance_dict = dict(name="Lance", age=18, habbit="eating")
```

### 多層字典

```python
name_dict = {
  "Lance": {
    "height":180,
    "age":18,
    "habbit":"eating"
  },
  "Amy": {
    "height":190,
    "age":10,
    "habbit":"hiking"
  }  
}

# 多層次字典要用多維度陣列存取
print(name_dict["Amy"]["age"]) # 10
```

### 【補充】可以利用zip快速建立字典

```python
dic = dict(zip('abcd', range(4)))
print(dic) # {'a': 0, 'b': 1, 'c': 2, 'd': 3}

dic = dict(zip('abcd', range(1,5)))
print(dic) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}

dic = dict(zip['a', 'b', 'c'], range(3)))
print(dic) # {'a': 0, 'b': 1, 'c': 2}
```

## IV. 利用`key`值找到相對應的`value`

利用`<dict_name>[<key>]` 或 `<dict_name>.get(<key>)`

```python
Lance_dict = {
  "name":"Lance",
  "age":18,
  "habbit":"eating"
}

print(Lance_dict["name"]) # Lance
print(Lance_dict.get("name")) # Lance
```

## V. 改變某`key`值所對應的`value`

直接利用`<dict_name>[<key>] = <new_value>` 即可

```python
Lance_dict = {
  "name":"Lance",
  "age":18,
  "habbit":"eating"
}

Lance_dict["age"] = 2023

print(Lance_dict.get("age")) # 2023
```

## VI. 新增新的`key`值和`value`

直接利用`<dict_name>[<new_key>] = <new_value>` 即可

```python
Lance_dict = {
  "name":"Lance",
  "age":18,
  "habbit":"eating"
}

Lance_dict["height"] = 180

print(Lance_dict) # {'name': 'Lance', 'age': 18, 'habbit': 'eating', 'height': 180}
```

## VII. 刪除特定`key`值和所對應的`value`

直接利用`del <dict_name>[<key>]` 或 `<dict_name>.pop(<key>)`

```python
Lance_dict = {
  "name":"Lance",
  "age":18,
  "habbit":"eating"
}

del (Lance_dict["habbit"])

print(Lance_dict) # {'name': 'Lance', 'age': 18}
```

> 若利用`<thisdict>.popitem()`會直接去除掉字典中最新(最後加進去)的那一筆

## VIII. 列出所有`key`值 或 `value`值

```python
Lance_dict = {
  "name":"Lance",
  "age":18,
  "habbit":"eating"
}

# 列出所有key值
for x in Lance_dict:
  print(x) 

# 列出所有value值
for x in Lance_dict:
  print(Lance_dict[x]) 

# 列出所有value值
for x in Lance_dict.values():
  print(x)

# 列出所有 key 及其相對應的 value，x:key y:value
for x, y in Lance_dict.items():
  print(x, y)
```

## IX. 排序字典中的資料

用`key`來排序

```python
dic = {3: 2, 1: 3, 2: 1}
dic = dict(sorted(dic.items()))
print(dic) # {1: 3, 2: 1, 3: 2}
```

用`value`來排序

```python
dic = {3: 2, 1: 3, 2: 1}
dic = dict(sorted(dic.items(), key=lambda x: x[1]))
print(dic) # {2: 1, 3: 2, 1: 3}
```

## X. 確認某`key`值是否存在字典內

```python
Lance_dict = {
  "name":"Lance",
  "age":18,
  "habbit":"eating"
}

if "weight" in Lance_dict:
  print("Yes")
```

## XI. 確認字典的總資料筆數

利用`len(<dict_name>)`

```python
Lance_dict = {
  "name":"Lance",
  "age":18,
  "habbit":"eating"
}

print(len(Lance_dict)) # 3
```

## XII. 複製整個字典

利用`<dict_name>.copy()`

```python
Lance_dict = {
  "name":"Lance",
  "age":18,
  "habbit":"eating"
}

mydict = Lance_dict .copy()

print(mydict) # {'name': 'Lance', 'age': 18, 'habbit': 'eating'}
```

## XIII. 清空字典中的資料

利用`<dict_name>.clear()`

```python
Lance_dict = {
  "name":"Lance",
  "age":18,
  "habbit":"eating"
}

mydict = Lance_dict.clear()

print(mydict) # None
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://simplife.gitbook.io/python/xin-shou-cun/zi-dian-ji-he.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
