一、什麼是Python字典
Python字典是一種可變容器模型,可以存儲任意類型的對象。它是一個鍵值對的集合,其中鍵是唯一的,不能重複,值是任意的對象。Python字典使用哈希表實現,因此查找操作的時間複雜度為O(1),具有快速存儲和訪問數據的優勢。
二、Python字典的基本操作
Python字典的基本操作包括增刪改查,以下是一些常用的操作方法:
# 創建一個字典
dic = {'name': 'Lucy', 'age': 18, 'sex': 'female'}
# 讀取字典中的值
print(dic['name']) # 輸出:Lucy
# 修改字典中的值
dic['age'] = 20
print(dic) # 輸出:{'name': 'Lucy', 'age': 20, 'sex': 'female'}
# 添加鍵值對
dic['address'] = 'Beijing'
print(dic) # 輸出:{'name': 'Lucy', 'age': 20, 'sex': 'female', 'address': 'Beijing'}
# 刪除鍵值對
del dic['sex']
print(dic) # 輸出:{'name': 'Lucy', 'age': 20, 'address': 'Beijing'}
三、Python字典的應用
1. 統計單詞出現的次數
Python字典可以用於統計文本中單詞出現的次數。以下是一個代碼示例:
text = "Python is a popular programming language that is easy to learn and use"
words = text.split()
dic = {}
for word in words:
if word in dic:
dic[word] += 1
else:
dic[word] = 1
print(dic)
輸出結果為:
{'Python': 1, 'is': 1, 'a': 1, 'popular': 1, 'programming': 1, 'language': 1, 'that': 1, 'easy': 1, 'to': 1, 'learn': 1, 'and': 1, 'use': 1}
2. 創建映射關係
Python字典可以用於創建映射關係,以下是一個代碼示例:
scores = {'Lucy': 90, 'Tom': 80, 'John': 70}
grades = {score: name for name, score in scores.items()}
print(grades) # 輸出:{90: 'Lucy', 80: 'Tom', 70: 'John'}
3. 分組數據
Python字典可以用於分組數據,以下是一個代碼示例:
students = [{'name': 'Lucy', 'age': 18, 'gender': 'female'},
{'name': 'Tom', 'age': 20, 'gender': 'male'},
{'name': 'John', 'age': 19, 'gender': 'male'},
{'name': 'Mary', 'age': 18, 'gender': 'female'}]
groups = {}
for student in students:
if student['age'] in groups:
groups[student['age']].append(student['name'])
else:
groups[student['age']] = [student['name']]
print(groups)
輸出結果為:
{18: ['Lucy', 'Mary'], 20: ['Tom'], 19: ['John']}
四、小結
Python字典是一種非常實用的數據結構,它可以高效地存儲和訪問數據,適用於大多數需要映射、關聯或者分組數據的場合。在實際應用中,我們可以靈活運用字典的多種操作方法解決各種問題。
原創文章,作者:IKLRQ,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/328919.html
微信掃一掃
支付寶掃一掃