一、什麼是字典?
在Python中,字典是一種可以存儲鍵-值對的數據結構,也稱為關聯數組、哈希表或映射。字典的內部實現使用了哈希表,因此能夠快速地進行搜索和插入操作。
字典的每個鍵唯一且不可變,一般情況下使用字元串或數字作為鍵,可以使用任何不可變的對象作為鍵,例如元組、布爾值等。值可以是任何類型的對象,包括字元串、數字、列表、元組和其它字典。
# 字典示例
d = {'name': 'Alice', 'age': 25, 'gender': 'female'}
print(d['name']) # 輸出 'Alice'
d['age'] = 26
print(d) # 輸出 {'name': 'Alice', 'age': 26, 'gender': 'female'}
二、字典的常見操作
1. 添加、刪除和修改字典元素
要添加一個鍵-值對,可以通過使用方括弧或者使用Python內置的`dict()`函數來實現。
d = {'name': 'Alice', 'age': 25, 'gender': 'female'}
# 添加新的鍵-值對
d['address'] = 'Beijing'
print(d) # 輸出 {'name': 'Alice', 'age': 25, 'gender': 'female', 'address': 'Beijing'}
# 刪除指定鍵-值對
del d['age']
print(d) # 輸出 {'name': 'Alice', 'gender': 'female', 'address': 'Beijing'}
# 修改指定鍵的值
d['gender'] = 'male'
print(d) # 輸出 {'name': 'Alice', 'gender': 'male', 'address': 'Beijing'}
2. 獲取字典元素
要獲取字典中的值,可以使用方括弧加鍵名,或者使用Python內置的`get()`方法。如果鍵不存在,則`get()`方法會返回None。
d = {'name': 'Alice', 'age': 25, 'gender': 'female'}
# 獲取指定鍵對應的值
print(d['name']) # 輸出 'Alice'
print(d.get('age')) # 輸出 25
print(d.get('address')) # 輸出 None
3. 遍歷字典
使用`for`循環遍歷字典時,默認情況下會遍歷字典的鍵。要遍歷字典的值或者鍵-值對,需要使用方法`values()`、`items()`。
d = {'name': 'Alice', 'age': 25, 'gender': 'female'}
# 遍歷字典的鍵
for key in d:
print(key)
# 遍歷字典的值
for value in d.values():
print(value)
# 遍歷字典的鍵-值對
for key, value in d.items():
print(key, value)
4. 判斷鍵是否在字典中
使用`in`關鍵字可以判斷一個鍵是否在字典中,另外也可以使用`not in`關鍵字來判斷一個鍵是否不在字典中。
d = {'name': 'Alice', 'age': 25, 'gender': 'female'}
if 'name' in d:
print('name exists in the dictionary')
if 'address' not in d:
print('address does not exist in the dictionary')
三、字典的高級操作
1. 使用`defaultdict`處理鍵的缺失
`defaultdict`是Python內置的一個字典子類,它可以自動為字典中缺失的鍵設置默認值。
from collections import defaultdict
d = defaultdict(int)
d['a'] = 1
d['b'] = 2
print(d['c']) # 輸出 0,因為'c'鍵不存在,使用int的默認值0
2. 使用`Counter`計數
`Counter`是Python內置的一個計數器工具,它可以統計一個可迭代對象中元素的出現次數,返回一個字典。
from collections import Counter
c = Counter(['red', 'blue', 'green', 'blue', 'red'])
print(c) # 輸出 Counter({'red': 2, 'blue': 2, 'green': 1})
3. 使用`dict()`和`zip()`創建字典
`dict()`可以將雙值序列、元組異構列表、關鍵字參數等各種形式的數據轉化為字典。
keys = ['a', 'b', 'c']
vals = [1, 2, 3]
d = dict(zip(keys, vals))
print(d) # 輸出 {'a': 1, 'b': 2, 'c': 3}
4. 使用字典生成式
字典生成式可以根據指定的規則生成字典,可以簡化循環和條件語句的操作。
d = {x: x**2 for x in range(1, 6)}
print(d) # 輸出 {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
總結
字典是Python中非常常用的數據結構,它能夠高效地存儲和查找鍵-值對,同時支持添加、刪除、修改、遍歷等操作。除了以上介紹的基本操作之外,Python還提供了一系列內置模塊和函數,使得字典的操作更加靈活和高級化。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/286300.html