ZetCode

Python dict 函数

上次修改时间:2025 年 4 月 11 日

本综合指南探讨 Python 的 dict 函数,该函数创建字典对象。我们将介绍创建方法、操作技巧和使用字典的实际示例。

基本定义

dict 函数创建一个新的字典对象。字典是键到值的可变映射。它们是无序的(Python 3.7+ 保留插入顺序),并且键必须是可哈希的。

主要特点:通过键快速查找、可变、可以嵌套,并支持各种创建方法。字典是 Python 的基本数据结构。

创建空字典

创建空字典最简单的方法是调用不带参数的 dict()。这等同于使用空花括号。

empty_dict.py
# Create empty dictionary
empty1 = dict()
empty2 = {}

print(empty1)  # {}
print(empty2)  # {}
print(type(empty1))  # <class 'dict'>
print(empty1 == empty2)  # True

这两种方法都创建相同的空字典对象。 dict() 构造函数更明确,而 {} 更简洁。

此示例显示了两种创建方法之间的类型检查和相等比较。它们产生相同的结果。

从键值对创建字典

您可以通过将关键字参数传递给 dict() 来创建字典。每个参数都成为字典中的一个键值对。

kw_dict.py
# 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() 可以从键值对的可迭代对象创建字典。每对通常是一个包含两个元素的元组或列表。

iterable_dict.py
# 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() 结合使用,您可以从两个单独的可迭代对象(一个用于键,一个用于值)创建字典。

zip_dict.py
# 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() 函数,但字典推导式是从任何可迭代对象创建字典的强大方法。

dict_comprehension.py
# 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} 模式。

它们可以包括条件并转换现有字典,使其在数据处理任务中非常灵活。

最佳实践

资料来源

作者

我的名字是 Jan Bodnar,我是一位充满热情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。迄今为止,我已经撰写了 1,400 多篇文章和 8 本电子书。我拥有超过十年的编程教学经验。

列出所有 Python 教程