Python 中的字典(python中的字典长什么样子)

liftword5个月前 (02-04)技术文章102

字典是 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}

相关文章

Python高效管理JSON文件:读写、更新、删除全攻略

引言:代码对 JSON 文件的常见操作(读取、写入、追加、删除、更新)的封装,每个方法都对常见的异常情况进行了处理,并且提供了详细的错误提示,失败的原因。代码封装如下:import json #to...

python学习笔记:06字典和集合(字典与集合的填空题答案python)

字典定义字典是另一种可变容器模型,且可存储任意类型对象。字典的数据结构为键值对结构{key:value}key必须是唯一的,且是不可变数据类型(如数值、字符串、元组),Value可以是任意类型的数据{...

Python.get()方法:改进您的字典操作

Python 字典是通用的数据结构,允许您使用键值对存储和检索数据。虽然访问字典中的值很简单,但有时可能会导致错误,或者在缺少键时需要额外检查。这就是 Python 的 .get() 方法的亮点。了...

Python dict 字典简介(python字典功能)

Python dic简介, <> 9 分钟阅读字典在Python中是必不可少的,因为它们的引入代表了编程的重大进步。在字典出现之前,编程要困难得多;您必须在列表或数组中维护所有数据,并记住...