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

liftword4个月前 (02-04)技术文章78

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

相关文章

学习编程第197天 python编程pop与popitem方法删除字典数据

今天学习的是刘金玉老师零基础Python教程第92期,主要内容是字典中的删除,pop方法与popitem方法。一、pop方法Pop方法属于字典自带的方法,只需要传入一个参数,这个参数是字典的键,这样就...

Python 字典的 10 种强大方法(python字典详解)

clear()clear() 方法用于从字典中删除所有项目。该方法返回一个空字典。在使用此方法之前,应该确保您不再需要字典中的任何项目。例:my_dict = { "name" : "John" ,...

每天3分钟Python基础-dict字典(dict的python)

Python是一门广泛使用的高级编程语言,它提供了各种数据结构,其中最受欢迎的是Python字典(Dictionary)。Python字典是一种无序、可变的数据结构,它使用键(Key)来索引值(Val...

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

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

详解Python字典格式化输出(python format 字典)

在Python中,字典的格式化输出有多种方法,常见的有下面几种方式:使用print()函数直接输出这是最简单的方法,直接使用print()打印字典my_dict = {'name':...

建议收藏丨纯知识点:Python基础—字典、集合操作大全

本文为纯知识点,预计需阅读二十分钟数据结构基本上就是——它们是可以处理一些 数据 的 结构 。或者说,它们是用来存储一组相关数据的。在Python中有四种内建的数据结构——列表、元组和字典,集合。我们...