如何在 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 的基本数据结构语法用元组填充它。指定字典中每个元组的键和值是构建元组字典的算法的一部分。这种适应性强的结构可以快速组织和检索信息。进行实验和练习以提高理解。

更新于: 2023-08-09

2K+ 阅读量

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.