Python dict 函数
上次修改时间:2025 年 4 月 11 日
本综合指南探讨 Python 的 dict 函数,该函数创建字典对象。我们将介绍创建方法、操作技巧和使用字典的实际示例。
基本定义
dict 函数创建一个新的字典对象。字典是键到值的可变映射。它们是无序的(Python 3.7+ 保留插入顺序),并且键必须是可哈希的。
主要特点:通过键快速查找、可变、可以嵌套,并支持各种创建方法。字典是 Python 的基本数据结构。
创建空字典
创建空字典最简单的方法是调用不带参数的 dict()。这等同于使用空花括号。
# Create empty dictionary
empty1 = dict()
empty2 = {}
print(empty1) # {}
print(empty2) # {}
print(type(empty1)) # <class 'dict'>
print(empty1 == empty2) # True
这两种方法都创建相同的空字典对象。 dict() 构造函数更明确,而 {} 更简洁。
此示例显示了两种创建方法之间的类型检查和相等比较。它们产生相同的结果。
从键值对创建字典
您可以通过将关键字参数传递给 dict() 来创建字典。每个参数都成为字典中的一个键值对。
# Create dictionary with keyword arguments
person = dict(name='John', age=30, city='New York')
print(person) # {'name': 'John', 'age': 30, 'city': 'New York'}
print(person['age']) # 30
# Keys must be valid Python identifiers
config = dict(max_connections=100, timeout=30)
print(config['timeout']) # 30
对于创建具有作为有效 Python 标识符的字符串键的字典,此方法非常简洁。在这种语法中,键不需要引号。
请注意,这种方法不适用于不是有效 Python 变量名的键(例如带有空格的字符串)。
从键值对的可迭代对象创建字典
dict() 可以从键值对的可迭代对象创建字典。每对通常是一个包含两个元素的元组或列表。
# From list of tuples
pairs = [('a', 1), ('b', 2), ('c', 3)]
mapping = dict(pairs)
print(mapping) # {'a': 1, 'b': 2, 'c': 3}
# From list of lists
matrix_coords = [['x', 10], ['y', 20], ['z', 30]]
coord_dict = dict(matrix_coords)
print(coord_dict['y']) # 20
当您有想要转换为字典的现有对序列时,此方法非常有用。这些对可以是任何两个元素的可迭代对象。
这种方法通常与 zip() 一起使用,以从单独的键和值列表创建字典。
从两个可迭代对象创建字典
通过将 dict() 与 zip() 结合使用,您可以从两个单独的可迭代对象(一个用于键,一个用于值)创建字典。
# From two lists
keys = ['name', 'age', 'job']
values = ['Alice', 25, 'Engineer']
person = dict(zip(keys, values))
print(person) # {'name': 'Alice', 'age': 25, 'job': 'Engineer'}
# From strings
headers = ['Content-Type', 'Content-Length', 'Server']
defaults = ['text/html', 0, 'Apache']
config = dict(zip(headers, defaults))
print(config['Server']) # 'Apache'
当您有应该组合成键值对的相关序列时,这种模式非常有用。 zip() 函数按位置配对元素。
生成的字典的长度将等于最短的输入可迭代对象。如果长度不同,则不会发生错误。
字典推导式
虽然不直接使用 dict() 函数,但字典推导式是从任何可迭代对象创建字典的强大方法。
# Create dictionary from range
squares = {x: x*x for x in range(6)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# Create dictionary with condition
even_squares = {x: x*x for x in range(10) if x % 2 == 0}
print(even_squares) # {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
# Transform existing dictionary
prices = {'apple': 0.5, 'banana': 0.25, 'orange': 0.75}
sale_prices = {k: v*0.9 for k, v in prices.items()}
print(sale_prices['apple']) # 0.45
字典推导式提供了一种简洁的创建字典的方法。它们遵循 {key_expr: value_expr for item in iterable} 模式。
它们可以包括条件并转换现有字典,使其在数据处理任务中非常灵活。
最佳实践
- 选择适当的创建方法: 为您的数据使用最易读的方法
- 空字典首选 dict(): 比 {} 更明确
- 简单情况下使用关键字参数: 当键是有效的标识符时
- 并行序列使用 zip(): 当您有单独的键和值列表时
- 考虑推导式: 用于转换和过滤创建
资料来源
作者
列出所有 Python 教程。