如何在 Python 中建立元組字典
本教程將介紹如何在 Python 中建立元組字典。這種資料結構儲存鍵值對。透過組合字典和元組,可以建立一個元組字典。其優點是以結構化的格式組織和訪問資料。可以輕鬆地為每個鍵表示多個值,例如學生成績或聯絡資訊。讓我們看看如何有效地儲存和檢索複雜資料。
語法
確保您的系統上已安裝 Python,因為它簡單易讀。使用以下語法建立元組字典
dictionary_name = {key1: (value1_1, value1_2, ...), key2:
(value2_1, value2_2, ...), ...}
示例
# Create a dictionary of students and their grades
students = {"John": (85, 90), "Emma": (92, 88), "Michael": (78, 80)}
# Accessing the values using keys
print(students["John"])
print(students["Emma"])
print(students["Michael"])
輸出
(85, 90) (92, 88) (78, 80)
初始化一個名為 students 的字典。鍵是學生姓名,值是表示其成績的元組。
演算法
請按照以下步驟建立元組字典
宣告一個空字典。
將鍵作為字典鍵,並將匹配的值作為元組新增到每個鍵值對。
對每個鍵值對重複此步驟。
將所有鍵值對作為元組新增到字典後,元組字典就生成了。現在它已準備好進行其他操作。為了避免覆蓋字典中任何當前值,鍵必須是唯一的。
示例
# Create a dictionary of books and their authors
books = {"Harry Potter": ("J.K. Rowling", 1997), "To Kill a Mockingbird":
("Harper Lee", 1960)}
# Adding a new book
books["1984"] = ("George Orll", 1949)
# Accessing the values using keys
print(books["Harry Potter"]) # Output: ("J.K. Rowling", 1997)
print(books.get("To Kill a Mockingbird"))
輸出
('J.K. Rowling', 1997)
('Harper Lee', 1960)
這裡,構建了一個名為 books 的字典。鍵表示書名,值是包含作者和出版年份的元組。您可以像第 3 行所示的那樣向字典中新增新的鍵值對。這個新新增的值可以使用索引以及 get() 方法訪問。
示例
# capitals and country dict
countries = {"USA": ("Washington D.C.", 328.2), "France":
("Paris", 67.06), "Japan": ("Tokyo", 126.5)}
# Removing a country
del countries["France"]
# Checking if a key exists
if "Japan" in countries:
print("Japan is in the dictionary.")
# Iterating over the dictionary
for country, (capital, population) in countries.items():
print(f"{capital} - {country} w/ {population} million.")
輸出
Japan is in the dictionary. Washington D.C. - USA w/ 328.2 million. Tokyo - Japan w/ 126.5 million.
del 關鍵字從字典中刪除鍵值對。可以驗證字典中是否存在某個鍵。如果要遍歷字典,請使用 items() 函式。
應用
元組字典可用於儲存員工記錄、產品目錄管理、教育設定和活動計劃。它在需要儲存姓名、年齡、職位、薪資和其他相關資料等資訊的同時,還包含學生成績和活動詳細資訊的場景中很有用。
employees = {
101: ('John Doe', 30, 'Software Engineer', 80000),
102: ('Alice Smith', 28, 'Data Analyst', 60000),
103: ('Bob Johnson', 35, 'Manager', 90000)
}
products = {
'product1': ('Laptop', 1200, 'Electronics', 50),
'product2': ('Shirt', 30, 'Apparel', 200),
'product3': ('Book', 15, 'Books', 1000)
}
countries = {
'USA': (331,002,651, 9833520, 'Washington D.C.'),
'China': (1439323776, 9596961, 'Beijing'),
'Brazil': (212559417, 8515767, 'Brasília')
}
grades = {
'Alice': (85, 90, 78, 93),
'Bob': (70, 80, 85, 75),
'Charlie': (95, 88, 92, 89)
}
events = {
'event1': ('2023-07-30', '10:00 AM', 'Conference Hall A', 'Workshop'),
'event2': ('2023-08-15', '7:30 PM', 'Auditorium', 'Concert'),
'event3': ('2023-09-05', '2:00 PM', 'Room 101', 'Seminar')
}
結論
本文深入探討了在 Python 中建立元組字典的方法。概括地說,構建一個字典並使用 Python 的基本資料結構語法用元組填充它。指定字典中每個元組的鍵和值是構建元組字典的演算法的一部分。這種適應性強的結構可以快速組織和檢索資訊。進行實驗和練習以提高理解。
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP