Python中的字典(Dictionary)

在Python中,字典(Dictionary)是一個常見的數據結構,它可以存儲任意類型的對象。

創建字典

字典由鍵和值組成,字典中所有鍵值均要放在 大括號 {} 裏面,鍵與值之間通過
冒號 : 分割,而每一對鍵值之間則通過 逗號 , 間隔起來,其格式如下:

d = {key1: value1, key2: value2, key3: value3}

一般在創建字典時,分爲創建空字典和非空字典,其創建方式如下:

# 創建空字典,有兩種方式
dict1= dict()
dict2 = {}

# 創建非空字典
dict3 = {"name": ["hello", "world"], "age": 13, 666: True}

在上面的 dict3 中,包含了 3 個鍵值對,其中鍵 "name" 對應值爲一個列表 ["hello", "world"],鍵 "age" 對應值爲一個整數 13,鍵 666 對應值爲一個布爾值True。

需要注意的是,字典中的鍵必須是唯一的,同時字典的鍵必須是不可變對象,如 字符串、數字 等,而鍵對應的值,則可以是任意數據類型。

到這裏,我們思考一個問題:元組是不可變對象,其能不能作爲字典的鍵呢?

只有滿足一定條件的元組,可以作爲字典的鍵。

如果元組中只包含字符串、數字等不可變對象,那麼才能夠作爲字典的鍵;如果元組中直接或間接的包含了可變對象,那麼就不能夠作爲字典的鍵。

>>> dict1 = {(1, "hi", (), True): "abc"}
>>>
>>> dict2 = {(1, "hi", [], True): "abc"}  # 元組中包含有列表
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

訪問字典中的值

在字典中,我們需要通過字典的鍵來訪問其對應的值。

  • 通過 dict[key] 取值
>>> dict1 = {"name": "wintest", "age": 13}
>>>
>>> dict1["name"]  # 取 key = "name" 的值
'wintest'
>>> dict1["age"]  # 取 key = "age" 的值
13
>>>
>>> dict1["xxx"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'xxx'

如果鍵不存在,那麼取值時就會報錯:KeyError: 'xxx'

  • 通過 get(key) 取值
>>> dict1 = {"name": "wintest", "age": 13}
>>>
>>> dict1.get("name")
'wintest'
>>> dict1.get("age")
13
>>>
>>> dict1.get("xxx")
>>>
>>> print(dict1.get("xxx"))
None
>>>

如果鍵不存在,那麼取值時會返回 None ,並不會報錯,這種情況下我們也可以讓其返回一個指定的值,該操作並不會影響字典的鍵值。如下:

>>> dict1 = {"name": "wintest", "age": 13}
>>>
>>> dict1.get("name", "123")  # 鍵存在時直接返回對應的值
'wintest'
>>> dict1.get("xxx", "123")  # 鍵不存在時返回指定的值
'123'
>>>
>>> dict1
{'name': 'wintest', 'age': 13}

更新字典

  • 通過 dict[key] 修改字典

在字典中,我們可以通過字典的鍵 dict[key] 來修改其對應值,如果鍵不存在,那麼就會把該鍵值對添加到字典中。

>>> dict1 = {"name": "wintest", "age": 13}
>>>
>>> dict1["xxx"] = "123"  # 添加鍵值對
>>>
>>> dict1
{'name': 'wintest', 'age': 13, 'xxx': '123'}
>>>
>>> dict1["age"] = 66  # 修改鍵的對應值
>>>
>>> dict1
{'name': 'wintest', 'age': 66, 'xxx': '123'}

在上面我們提到,字典中的鍵必須是唯一的,如果在創建字典時對同一個鍵賦值多次,那麼只有最後一個值會被記住,因爲對同一個鍵多次賦值時,其實就相當於 dict[key] 對字典進行修改。

  • 通過 update(dict) 修改字典

字典中的 update() 方法,傳入參數需要是一個新字典,該操作會把新字典中的鍵值對更新到原字典中。

>>> dict1 = {"name": "wintest", "age": 13}
>>>
>>> dict2 = {"name": "hihihi", "sex": "女"}
>>>
>>> dict1.update(dict2)  # 把 dict2 中鍵值對,更新到 dict1 中
>>>
>>> dict1
{'name': 'hihihi', 'age': 13, 'sex': '女'}

刪除字典元素

  • 通過 del 刪除字典中的鍵值對
>>> dict1 = {"name": "wintest", "age": 13}
>>>
>>> del dict1["name"]
>>>
>>> dict1
{'age': 13}
>>>
>>> del dict1["name"]  # 如果鍵不存在會報錯
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'name'
  • 通過 pop() 刪除字典中的鍵值對
>>> dict1 = {"name": "wintest", "age": 13}
>>>
>>> dict1.pop("name")
'wintest'
>>>
>>> dict1
{'age': 13}
>>>

使用 pop() 方法有一個好處,如果要刪除的鍵值對不存在,那麼就可以設置指定返回值來避免出現報錯,如下:

>>> dict1 = {"name": "wintest", "age": 13}
>>>
>>> dict1.pop("xxx")  # 鍵不存在,沒有指定返回值
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'xxx'
>>>
>>> dict1.pop("xxx", "不存在的key")  # 鍵不存在,指定返回值
'不存在的key'
  • 通過 del 刪除整個字典
>>> dict1 = {"name": "wintest", "age": 13}
>>>
>>> del dict1  # 刪除字典
>>>
>>> dict1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'dict1' is not defined
  • 通過 clear 清空字典
>>> dict1 = {"name": "wintest", "age": 13}
>>>
>>> dict1.clear()
>>>
>>> dict1
{}

字典的遍歷

字典在遍歷時,也可以類似列表、集合等數據類型,通過關鍵字 in 來實現。

dict1 = {"name": "wintest", "age": 13}

for key in dict1:
    print(key, dict1[key])

上面對字典遍歷時,只會對字典的鍵進行遍歷,需通過鍵去手動獲取其對應的值,因此,當我們判斷某元素是否在字典中時(如 xxx in dict),其實是判斷字典所有鍵中,是否包含有該元素。

我們也可以使用 dict1.items() ,先以列表返回一個視圖對象,然後對其遍歷時,可以直接獲取到字典中的鍵和值,如下:

dict1 = {"name": "wintest", "age": 13}

print(dict1.items())  # dict_items([('name', 'wintest'), ('age', 13)])

for key, value in dict1.items():
    print(key, value)

字典函數&方法

函數 & 方法 描述
len(dict) 返回字典中鍵值對的個數
dict.get(key, default=None) 返回字典中鍵的對應值
dict.update(dict2) 把字典dict2的鍵值對更新到dict裏
dict.pop(key) 刪除字典中指定鍵,返回被刪除鍵的對應值
dict.clear() 清空字典
dict.items() 返回字典中所有的鍵值對
dict.keys() 返回字典中所有的鍵
dict.values() 返回字典中所有鍵的對應值
dict.copy() 複製字典,使用的是淺拷貝
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章