一、字典基礎操作
Python中的字典是一種可變容器模型,可以存儲任意類型對象。字典是由鍵和對應值組成的鍵值對集合,字典的鍵是唯一的不可變對象,如字元串、數字或元組,而值則可以是任意對象。字典是無序的,所以不能通過下標索引來訪問其中的元素。在字典中查找元素的時間複雜度是O(1),效率非常高。
創建字典可以使用花括弧{}或者dict()函數,例如:
{
'name': 'John',
'age': 25,
'city': 'New York'
}
dict(name='John', age=25, city='New York')
訪問字典中的元素可以通過鍵來實現,例如:
person = {'name': 'John', 'age': 25}
print(person['name']) # 輸出 John
print(person.get('gender', 'Male')) # 輸出 Male,因為 gender 不存在
更新字典可以直接使用等號賦值或者update()方法,例如:
person = {'name': 'John', 'age': 25}
person['age'] = 26
person.update({'gender': 'Male'})
print(person) # 輸出 {'name': 'John', 'age': 26, 'gender': 'Male'}
刪除字典中的元素可以使用del語句或pop()方法,例如:
person = {'name': 'John', 'age': 25}
del person['age']
gender = person.pop('gender', 'Unknown')
print(person) # 輸出 {'name': 'John'}
print(gender) # 輸出 Unknown,因為 gender 不存在
二、字典常用方法
Python字典提供了許多常用的方法,如keys()返回所有鍵的列表,values()返回所有值的列表,items()返回所有鍵值對的元組列表,例如:
person = {'name': 'John', 'age': 25}
print(person.keys()) # 輸出 ['name', 'age']
print(person.values()) # 輸出 ['John', 25]
print(person.items()) # 輸出 [('name', 'John'), ('age', 25)]
字典還提供了一些其他常用方法,如clear()用於清空字典,copy()用於複製字典,setdefault()用於獲取值,如果鍵不存在則設置默認值,例如:
person = {'name': 'John', 'age': 25}
person.clear()
print(person) # 輸出 {}
person = {'name': 'John', 'age': 25}
person_copy = person.copy()
person.setdefault('gender', 'Male')
age = person.setdefault('age', 26)
print(person) # 輸出 {'name': 'John', 'age': 25, 'gender': 'Male'}
print(person_copy) # 輸出 {'name': 'John', 'age': 25}
print(age) # 輸出 25,因為 age 已經存在
三、騷操作
除了基礎和常用的方法,Python字典還可以實現許多騷操作:
1. 字典推導式
類似於列表推導式,可以用於快速創建字典,例如:
{i: i ** 2 for i in range(5)} # 輸出 {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
2. defaultdict
defaultdict是collections模塊中的一個類,它可以設置默認值,當字典中的鍵不存在時,可以返回默認值而不是報錯。例如:
from collections import defaultdict
nums = defaultdict(lambda: 0)
nums[1] += 1
nums[2] += 1
print(nums[1], nums[2], nums[3]) # 輸出 1 1 0
3. Counter
Counter是collections模塊中的另一個類,它可以用於計算可迭代對象中每個元素出現的次數。例如:
from collections import Counter
nums = [1, 2, 3, 1, 2, 1]
count = Counter(nums)
print(count) # 輸出 Counter({1: 3, 2: 2, 3: 1})
4. 字典的比較和排序
Python提供了比較和排序字典的方法,通過key參數可以指定比較的鍵。例如:
person1 = {'name': 'John', 'age': 25}
person2 = {'name': 'Tom', 'age': 30}
person3 = {'name': 'Lucy', 'age': 22}
people = [person1, person2, person3]
people_sorted = sorted(people, key=lambda x: x['age'])
print(people_sorted) # 輸出 [{'name': 'Lucy', 'age': 22}, {'name': 'John', 'age': 25}, {'name': 'Tom', 'age': 30}]
完整代碼示例:
from collections import defaultdict, Counter
# 字典基礎操作
person = {'name': 'John', 'age': 25}
print(person['name']) # 輸出 John
print(person.get('gender', 'Male')) # 輸出 Male,因為 gender 不存在
person['age'] = 26
person.update({'gender': 'Male'})
print(person) # 輸出 {'name': 'John', 'age': 26, 'gender': 'Male'}
del person['age']
gender = person.pop('gender', 'Unknown')
print(person) # 輸出 {'name': 'John'}
print(gender) # 輸出 Unknown,因為 gender 不存在
# 字典常用方法
person = {'name': 'John', 'age': 25}
print(person.keys()) # 輸出 ['name', 'age']
print(person.values()) # 輸出 ['John', 25]
print(person.items()) # 輸出 [('name', 'John'), ('age', 25)]
person.clear()
print(person) # 輸出 {}
person = {'name': 'John', 'age': 25}
person_copy = person.copy()
person.setdefault('gender', 'Male')
age = person.setdefault('age', 26)
print(person) # 輸出 {'name': 'John', 'age': 25, 'gender': 'Male'}
print(person_copy) # 輸出 {'name': 'John', 'age': 25}
print(age) # 輸出 25,因為 age 已經存在
# 騷操作
{ i: i ** 2 for i in range(5) } # 輸出 {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
nums = defaultdict(lambda: 0)
nums[1] += 1
nums[2] += 1
print(nums[1], nums[2], nums[3]) # 輸出 1 1 0
nums = [1, 2, 3, 1, 2, 1]
count = Counter(nums)
print(count) # 輸出 Counter({1: 3, 2: 2, 3: 1})
person1 = {'name': 'John', 'age': 25}
person2 = {'name': 'Tom', 'age': 30}
person3 = {'name': 'Lucy', 'age': 22}
people = [person1, person2, person3]
people_sorted = sorted(people, key=lambda x: x['age'])
print(people_sorted) # 輸出 [{'name': 'Lucy', 'age': 22}, {'name': 'John', 'age': 25}, {'name': 'Tom', 'age': 30}]
原創文章,作者:IOMVV,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/317111.html