Python 中的字典(python中的字典长什么样子)
字典是 Python 中的一种内置数据结构,允许您将数据存储在键值对中。这种类型的数据结构具有高度的通用性,支持基于唯一键高效检索、插入和删除数据。字典非常适合表示结构化数据,其中每个键都可以与特定值相关联,这使得它们对于编程中的各种应用程序至关重要。
1. 创建词典
可以通过将键值对放在大括号 {} 内来创建字典,键和值用冒号分隔。或者,您可以使用 dict() 构造函数。
示例:创建简单词典
# Creating a dictionary to store fruit prices
fruit_prices = {
"apple": 0.60,
"banana": 0.50,
"cherry": 1.00
}
print(fruit_prices)
输出:
{'apple': 0.6, 'banana': 0.5, 'cherry': 1.0}
2. 访问值
可以使用带有方括号 [] 的相应键来访问字典中的值,也可以使用 get() 方法,这种方法更安全,因为它允许您在键不存在时指定默认值。
示例:访问字典中的值
# Accessing prices
apple_price = fruit_prices["apple"] # Using brackets
banana_price = fruit_prices.get("banana", "Not found") # Using get()
print("Apple Price:", apple_price)
print("Banana Price:", banana_price)
输出:
Apple Price: 0.6
Banana Price: 0.5
3. 添加和更新条目
只需为指定键分配值,即可向字典添加新的键值对或更新现有键值对。
示例:添加和更新条目
# Adding a new fruit price
fruit_prices["orange"] = 0.80
# Updating an existing fruit price
fruit_prices["banana"] = 0.60
print(fruit_prices)
输出:
{'apple': 0.6, 'banana': 0.6, 'cherry': 1.0, 'orange': 0.8}
4. 删除条目
可以使用 del 语句或 pop() 方法从字典中删除键值对。pop() 方法允许在删除条目时检索值。
示例:删除条目
# Removing an entry using del
del fruit_prices["cherry"]
# Removing an entry using pop
banana_price = fruit_prices.pop("banana", "Not found")
print(fruit_prices)
print("Removed Banana Price:", banana_price)
输出:
{'apple': 0.6, 'orange': 0.8}
Removed Banana Price: 0.6
4-5. 遍历字典
您可以使用循环遍历字典中的键、值或键值对。这对于处理或显示数据非常有用。
示例:遍历字典
# Iterating through keys and values
for fruit, price in fruit_prices.items():
print(f"{fruit}: ${price:.2f}")
输出:
apple: $0.60
orange: $0.80
6. 嵌套词典
字典还可以包含其他字典作为值,从而允许使用对分层关系进行建模的复杂数据结构。
示例:嵌套词典
# Creating a nested dictionary for a book collection
book_collection = {
"978-3-16-148410-0": {
"title": "Python Programming",
"author": "John Doe",
"year": 2020
},
"978-0-13-419044-0": {
"title": "Data Science Handbook",
"author": "Jane Smith",
"year": 2019
}
}
# Accessing nested dictionary values
book_title = book_collection["978-3-16-148410-0"]["title"]
print("Book Title:", book_title)
输出:
Book Title: Python Programming
7. 字典推导式
与列表推导式类似,Python 支持字典推导式,允许从可迭代对象简洁地创建字典。
示例:字典推导
# Creating a dictionary of squares for numbers 1 to 5
squares = {x: x**2 for x in range(1, 6)}
print(squares)
输出:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}