# Python 字典
> 原文: [https://thepythonguru.com/python-dictionaries/](https://thepythonguru.com/python-dictionaries/)
* * *
于 2020 年 1 月 7 日更新
* * *
字典是一種 python 數據類型,用于存儲鍵值對。 它使您可以使用鍵快速檢索,添加,刪除,修改值。 字典與我們在其他語言上稱為關聯數組或哈希的非常相似。
**注意**:
字典是可變的。
## 創建字典
* * *
可以使用一對大括號(`{}`)創建字典。 字典中的每個項目都由一個鍵,一個冒號,一個值組成。 每個項目都用逗號(`,`)分隔。 讓我們舉個例子。
```py
friends = {
'tom' : '111-222-333',
'jerry' : '666-33-111'
}
```
這里`friends`是有兩個項目的字典。 需要注意的一點是,鍵必須是可哈希的類型,但是值可以是任何類型。 字典中的每個鍵都必須是唯一的。
```py
>>> dict_emp = {} # this will create an empty dictionary
```
## 檢索,修改和向字典中添加元素
* * *
要從字典中獲取項目,請使用以下語法:
```py
>>> dictionary_name['key']
```
```py
>>> friends['tom']
'111-222-333'
```
如果字典中存在鍵,則將返回值,否則將引發`KeyError`異常。 要添加或修改項目,請使用以下語法:
```py
>>> dictionary_name['newkey'] = 'newvalue'
```
```py
>>> friends['bob'] = '888-999-666'
>>> friends
?{'tom': '111-222-333', 'bob': '888-999-666', 'jerry': '666-33-111'}
```
## 從字典中刪除項目
* * *
```py
>>> del dictionary_name['key']
```
```py
>>>??del friends['bob']
>>> ?friends
{'tom': '111-222-333', 'jerry': '666-33-111'}
```
如果找到鍵,則該項目將被刪除,否則將拋出`KeyError`異常。
## 遍歷字典中的項目
* * *
您可以使用`for`循環遍歷字典中的元素。
```py
>>> friends = {
... 'tom' : '111-222-333',
... 'jerry' : '666-33-111'
...}
>>>
>>> for key in friends:
... print(key, ":", friends[key])
...
tom : 111-222-333
jerry : 666-33-111
>>>
>>>
```
## 查找字典的長度
* * *
您可以使用`len()`函數查找字典的長度。
```py
>>> len(friends)
2
```
## `in`和`not in`運算符
* * *
`in`和`not in`運算符檢查字典中是否存在鍵。
```py
>>> 'tom' in friends
True
>>> 'tom' not in friends
False
```
## 字典中的相等測試
* * *
`==`和`!=`運算符告訴字典是否包含相同的項目。
```py
>>> d1 = {"mike":41, "bob":3}
>>> d2 = {"bob":3, "mike":41}
>>> d1 == d2
True
>>> d1 != d2
False
>>>
```
**注意**:
您不能使用`<`,`>`,`>=`,`<=`等其他關系運算符來比較字典。
## 字典方法
* * *
Python 提供了幾種內置的方法來處理字典。
| 方法 | 描述 |
| --- | --- |
| `popitem()` | 返回字典中隨機選擇的項目,并刪除所選項目。 |
| `clear()` | 刪除字典中的所有內容 |
| `keys()` | 以元組形式返回字典中的鍵 |
| `values()` | 以元組形式返回字典中的值 |
| `get(key)` | 鍵的返回值,如果找不到鍵,則返回`None`,而不是引發`KeyError`異常 |
| `pop(key)` | 從字典中刪除該項目,如果找不到該鍵,則會拋出`KeyError` |
```py
>>> friends = {'tom': '111-222-333', 'bob': '888-999-666', 'jerry': '666-33-111'}
>>>
>>> friends.popitem()
('tom', '111-222-333')
>>>
>>>?friends.clear()
>>>
>>>?friends
{}
>>>
>>>?friends = {'tom': '111-222-333', 'bob': '888-999-666', 'jerry': '666-33-111'}
>>>
>>> friends.keys()
dict_keys(['tom', 'bob', 'jerry'])
>>>
>>> friends.values()
dict_values(['111-222-333', '888-999-666', '666-33-111'])
>>>
>>>?friends.get('tom')
'111-222-333'
>>>
>>>?friends.get('mike', 'Not Exists')
'Not Exists'
>>>
>>>?friends.pop('bob')
'888-999-666'
>>>
>>> friends
{'tom': '111-222-333', 'jerry': '666-33-111'}
```
在下一篇文章中,我們將學習 [Python 元組](/python-tuples/)。
* * *
* * *
- 初級 Python
- python 入門
- 安裝 Python3
- 運行 python 程序
- 數據類型和變量
- Python 數字
- Python 字符串
- Python 列表
- Python 字典
- Python 元組
- 數據類型轉換
- Python 控制語句
- Python 函數
- Python 循環
- Python 數學函數
- Python 生成隨機數
- Python 文件處理
- Python 對象和類
- Python 運算符重載
- Python 繼承與多態
- Python 異常處理
- Python 模塊
- 高級 Python
- Python *args和**kwargs
- Python 生成器
- Python 正則表達式
- 使用 PIP 在 python 中安裝包
- Python virtualenv指南
- Python 遞歸函數
- __name__ == "__main__"是什么?
- Python Lambda 函數
- Python 字符串格式化
- Python 內置函數和方法
- Python abs()函數
- Python bin()函數
- Python id()函數
- Python map()函數
- Python zip()函數
- Python filter()函數
- Python reduce()函數
- Python sorted()函數
- Python enumerate()函數
- Python reversed()函數
- Python range()函數
- Python sum()函數
- Python max()函數
- Python min()函數
- Python eval()函數
- Python len()函數
- Python ord()函數
- Python chr()函數
- Python any()函數
- Python all()函數
- Python globals()函數
- Python locals()函數
- 數據庫訪問
- 安裝 Python MySQLdb
- 連接到數據庫
- MySQLdb 獲取結果
- 插入行
- 處理錯誤
- 使用fetchone()和fetchmany()獲取記錄
- 常見做法
- Python:如何讀取和寫入文件
- Python:如何讀取和寫入 CSV 文件
- 用 Python 讀寫 JSON
- 用 Python 轉儲對象