一、Python 字典基礎
Python 的字典是一種可變、無序的映射類型,其內部所有元素都是鍵值對。這裡的關鍵操作技巧就是對字典的基本的增、刪、改、查操作。
1、增加鍵值對:可以使用賦值語句直接添加鍵值對,如:
>>> dict = {'name': 'Tom', 'age': 20} >>> dict['gender'] = 'M' >>> print(dict) {'name': 'Tom', 'age': 20, 'gender': 'M'}
2、刪除鍵值對:可以使用 del 或 pop 函數刪除指定鍵值對,其中 pop 函數會返回被刪除的鍵值對的值,如:
>>> del dict['age'] >>> print(dict) {'name': 'Tom', 'gender': 'M'} >>> gender = dict.pop('gender') >>> print(dict) {'name': 'Tom'} >>> print(gender) M
3、修改鍵值對:可以直接使用賦值語句修改已有的鍵值對,如:
>>> dict['name'] = 'Mike' >>> print(dict) {'name': 'Mike'}
4、查詢鍵值對:可以直接通過鍵訪問對應的值,如:
>>> print(dict['name']) Mike
二、Python 字典高級操作
除了基於字典的基本操作,Python 還提供了一些字典高級操作來更好地支持字典的一些場景需求。
1. 字典合併
有時候,我們需要將多個字典合併成一個字典,Python 也提供了方便的方式來實現這個需求,如下:
>>> dict1 = {'name': 'Tom'} >>> dict2 = {'age': 20, 'gender': 'M'} >>> dict3 = {'height': 170} >>> dict4 = {**dict1, **dict2, **dict3} >>> print(dict4) {'name': 'Tom', 'age': 20, 'gender': 'M', 'height': 170}
2. 字典遍歷
當我們需要遍歷字典時,可以使用 for 循環結合 items、keys 或 values 函數進行操作。items 函數會返回一個包含所有 (key, value) 對元組的列表,keys 函數會返回一個包含所有鍵的列表,values 函數會返回一個包含所有值的列表,如下:
>>> dict = {'name': 'Tom', 'age': 20, 'gender': 'M'} >>> for k, v in dict.items(): ... print(k, v) name Tom age 20 gender M >>> for k in dict.keys(): ... print(k) name age gender >>> for v in dict.values(): ... print(v) Tom 20 M
3. 字典推導式
類似於列表推導式,Python 中也支持字典推導式,可以快速生成字典。字典推導式的語法為 {key: value for key, value in iterable},其中 iterable 需要返回一個包含鍵值對元組的可迭代對象。如下:
>>> data = [('name', 'Tom'), ('age', 20), ('gender', 'M')] >>> dict = {k: v for k, v in data} >>> print(dict) {'name': 'Tom', 'age': 20, 'gender': 'M'}
三、Python 字典應用場景
Python 字典不僅僅用來存儲鍵值對,其具有良好的映射性質,可以應用於許多場景。
1. 統計字元出現次數
Python 字典可以非常方便地用來統計字元串中出現的所有字元以及出現次數。Python 標準庫中的 collections 模塊提供了一個 Counter 類用來實現這個需求,如下:
>>> from collections import Counter >>> s = 'hello world' >>> c = Counter(s) >>> print(dict(c)) {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
2. 構建 API 響應數據
在 構建 API 響應數據 時,往往需要將數據以 JSON 格式返回,而在 Python 中,JSON 格式其實就是字典格式。因此,可以通過 Python 字典來完美地構建 API 響應數據。如下:
data = { 'name': 'Tom', 'age': 20, 'gender': 'M', 'education': { 'university': 'Tsinghua University', 'major': 'Computer Science', 'graduation_date': '2022-06-30' } } response = {'code': 0, 'success': True, 'data': data} print(response) {'code': 0, 'success': True, 'data': {'name': 'Tom', 'age': 20, 'gender': 'M', 'education': {'university': 'Tsinghua University', 'major': 'Computer Science', 'graduation_date': '2022-06-30'}}}
3. 對象屬性映射
在 Python 中,可以通過內置函數 vars 獲取對象的屬性和屬性值信息,並將其映射到字典中,如下:
class Student: def __init__(self, name, age, gender, university, major, graduation_date): self.name = name self.age = age self.gender = gender self.education = {'university': university, 'major': major, 'graduation_date': graduation_date} student = Student('Tom', 20, 'M', 'Tsinghua University', 'Computer Science', '2022-06-30') print(vars(student)) {'name': 'Tom', 'age': 20, 'gender': 'M', 'education': {'university': 'Tsinghua University', 'major': 'Computer Science', 'graduation_date': '2022-06-30'}}
結語
Python 字典是 Python 編程中不可或缺的一部分,掌握 Python 字典操作技巧有助於提升 Python 程序的性能和可讀性。通過上面的闡述,相信讀者對 Python 字典的基本操作、高級操作、應用場景都有了更深入的理解。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/237815.html