在Python語言中,Dictionary是一種非常有用的數據類型,尤其是在數據存儲和檢索方面。Dictionary是一種以鍵值對形式存儲數據的數據結構,它支持快速的檢索和插入、刪除操作。本文將從多個方面對Python Dictionary做詳細的闡述。
一、 Dictionary的基本操作
1)創建Dictionary
dict1 = {'name': 'Bob', 'age': 20, 'gender': 'male'}
2)訪問Dictionary元素
print(dict1['name'])
3)更新Dictionary元素
dict1['age'] = 21
4)刪除Dictionary元素
del dict1['gender']
5)遍歷Dictionary
for key, value in dict1.items(): print(key, value)
二、 Dictionary的常見應用
1. 計數
可以利用Dictionary進行統計一個序列中各個元素出現的次數。
words = ['apple', 'banana', 'apple', 'orange', 'banana', 'banana'] word_count = {} for word in words: if word in word_count: word_count[word] += 1 else: word_count[word] = 1 print(word_count)
2. 緩存
Dictionary可以用來存儲經常使用的計算值,以避免重複計算。
cache_dict = {} def complex_calculation(n): if n in cache_dict: print("Cache hit!") return cache_dict[n] else: print("Cache miss") result = # do some complex calculation cache_dict[n] = result return result
3. 分組
可以利用Dictionary將一組數據按照指定規則進行分組。
data = [ {'name': 'Bob', 'age': 20, 'gender': 'male'}, {'name': 'Alice', 'age': 21, 'gender': 'female'}, {'name': 'Charlie', 'age': 22, 'gender': 'male'}, {'name': 'David', 'age': 23, 'gender': 'male'}, {'name': 'Eve', 'age': 24, 'gender': 'female'} ] group_dict = {} for d in data: if d['gender'] in group_dict: group_dict[d['gender']].append(d) else: group_dict[d['gender']] = [d] print(group_dict)
三、 使用Dictionary解決實際問題的例子
1. 統計詞頻
假設有一篇文章,需要計算其中每個單詞出現的次數。
with open('article.txt', 'r') as f: words = f.read().split() word_count = {} for word in words: if word in word_count: word_count[word] += 1 else: word_count[word] = 1
2. 統計電影票房
假設有一組電影信息數據,包括電影名稱和票房,需要根據電影名稱將票房進行統計。
movie_data = [ {'name': 'Avatar', 'box_office': 2784}, {'name': 'Titanic', 'box_office': 2187}, {'name': 'Star Wars: The Force Awakens', 'box_office': 2068}, {'name': 'Avengers: Endgame', 'box_office': 2797}, {'name': 'Avatar', 'box_office': 2746}, {'name': 'The Lion King', 'box_office': 1657}, {'name': 'The Avengers', 'box_office': 1519} ] box_office_dict = {} for movie in movie_data: if movie['name'] in box_office_dict: box_office_dict[movie['name']] += movie['box_office'] else: box_office_dict[movie['name']] = movie['box_office']
3. 基於Dictionary實現用戶系統
假設需要實現一個簡單的用戶系統,包括註冊、登錄和退出登錄等功能。
users = {} def register(): username = input("請輸入用戶名:") password = input("請輸入密碼:") if username in users: print("該用戶名已被註冊") else: users[username] = password print("註冊成功") def login(): username = input("請輸入用戶名:") password = input("請輸入密碼:") if username in users and users[username] == password: print("登錄成功") else: print("用戶名或密碼錯誤") def logout(): print("退出登錄") while True: choice = input("請選擇操作:1. 註冊,2. 登錄,3. 退出登錄") if choice == '1': register() elif choice == '2': login() elif choice == '3': logout() break
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/159359.html