Skip to content

Python 字典

字典(Dictionary)是 Python 中基本的一种映射类型(Mapping Type)。它们存储键值对(key-value pairs)的集合,其中每个键(key)必须是唯一的且不可变(immutable)(如字符串 string、数字 number 或只包含不可变元素的元组 tuple)。值(value)可以是任何类型,且可以重复。

字典使用花括号 {} 定义。一个空字典是 {}。字典项之间用逗号 , 分隔,键和值之间用冒号 : 分隔。

# 创建字典
empty_dict = {}
student = {
'name': 'Zara',
'age': 17,
'courses': ['Math', 'Physics']
}
config = dict(host='localhost', port=8080) # Alternative using dict()

重要提示:从 Python 3.7+ 开始,标准字典会记住项目的插入顺序(insertion order)。在早期版本(3.6 及以下),字典是无序的(unordered)。

使用方括号 [] 表示法访问与键关联的值。

student = {'name': 'Zara', 'age': 17, 'class': 'First'}
print(f"Student's Name: {student['name']}")
print(f"Student's Age: {student['age']}")

输出:

Student's Name: Zara
Student's Age: 17

使用 [] 访问不存在的键将引发 KeyError(键错误)。

student = {'name': 'Zara', 'age': 17}
# This will cause an error:
# print(f"Student's Grade: {student['grade']}")

为了安全地访问键,可以使用 get() 方法,如果找不到键,该方法会返回 None(或者一个指定的默认值)。

grade = student.get('grade') # Returns None
default_grade = student.get('grade', 'N/A') # Returns 'N/A'
print(f"Grade (safe access): {grade}")
print(f"Grade (with default): {default_grade}")

您可以使用赋值运算符 = 和方括号表示法来添加新的键值对或修改现有的键值对。

student = {'name': 'Zara', 'age': 17, 'class': 'First'}
# Update existing entry
student['age'] = 18
# Add new entry
student['school'] = "Springfield High"
student['contact'] = {'email': 'zara@example.com'} # Values can be complex
print(f"Updated Age: {student['age']}")
print(f"School: {student['school']}")
print(f"Contact Info: {student['contact']}")
print(f"Full dictionary: {student}")

输出:

Updated Age: 18
School: Springfield High
Contact Info: {'email': 'zara@example.com'}
Full dictionary: {'name': 'Zara', 'age': 18, 'class': 'First', 'school': 'Springfield High', 'contact': {'email': 'zara@example.com'}}

您还可以使用 update() 方法或合并运算符 |(Python 3.9+)来合并字典。

more_info = {'city': 'Shelbyville', 'age': 19} # Note 'age' overlaps
student.update(more_info) # Updates existing keys, adds new ones
print(f"After update(): {student}")
# Using merge operator (Python 3.9+)
extra = {'country': 'USA'}
merged_student = student | extra
print(f"After merge |: {merged_student}")

您可以移除单个键值对,清空整个字典,或删除字典对象本身。

student = {'name': 'Zara', 'age': 18, 'class': 'First', 'school': 'Springfield High'}
# Remove entry with key 'class' using del
del student['class']
print(f"After del student['class']: {student}")
# Remove entry with key 'school' using pop() (returns the value)
school = student.pop('school')
print(f"Removed school: {school}")
print(f"After pop('school'): {student}")
# Remove the last inserted item (Python 3.7+)
last_item = student.popitem()
print(f"Removed last item: {last_item}")
print(f"After popitem(): {student}")
# Remove all entries from the dictionary
student.clear()
print(f"After clear(): {student}")
# Delete the dictionary object entirely
del student
# print(student) # This would now raise a NameError

输出(对于 popitem,输出可能会因插入顺序略有不同):

After del student['class']: {'name': 'Zara', 'age': 18, 'school': 'Springfield High'}
Removed school: Springfield High
After pop('school'): {'name': 'Zara', 'age': 18}
Removed last item: ('age', 18)
After popitem(): {'name': 'Zara'}
After clear(): {}

字典键有两个重要的属性:

  1. 键必须是唯一的:一个字典不能有重复的键。如果为现有键分配一个值,则原始值将被覆盖。
  2. 键必须是不可变的:键必须是可哈希(hashable)的类型。这包括数字(int、float)、字符串、布尔值以及只包含不可变元素的元组。列表(list)、字典或集合(set)不能用作键,因为它们是可变的(mutable)(它们的内容可以改变)。

示例(重复的键):

dict_dup = {
'name': 'Zara',
'age': 7,
'name': 'Manni' # This assignment overwrites the previous 'name'
}
print(f"dict_dup['name']: {dict_dup['name']}") # Output: Manni

示例(不可变键):

# Valid keys
valid_keys = {
10: 'Number',
'user': 'Admin',
(1, 2): 'Tuple Key',
True: 'Boolean Key'
}
print(valid_keys)
# Invalid key (list is mutable)
# invalid_keys = {
# ['list_key']: 'This will fail'
# }
# TypeError: unhashable type: 'list'

Python 字典支持各种内置函数和方法:

函数描述
len(dict)返回字典中的键值对(项)数量。
str(dict)返回字典的可打印字符串表示。
type(variable)返回变量的类型。如果是字典,返回 <class 'dict'>。
方法描述
dict.clear()移除字典中的所有项。
dict.copy()返回字典的浅拷贝(shallow copy)。
dict.fromkeys(seq[, value])创建一个新字典,以序列 seq 中的元素作为键,以 value 作为值(默认为 None)。(类方法)
dict.get(key[, default])如果字典中存在 key,返回其对应的值,否则返回 default。如果 default 未提供,默认为 None。
dict.items()返回一个视图对象,显示字典中键值对元组的列表。字典的变化会反映在视图中。
dict.keys()返回一个视图对象,显示字典键的列表。字典的变化会反映在视图中。
dict.values()返回一个视图对象,显示字典值的列表。字典的变化会反映在视图中。
dict.pop(key[, default])移除指定键及其对应的值,并返回该值。如果找不到键,且提供了 default,则返回 default;否则引发 KeyError。
dict.popitem()移除并返回最后插入的键值对(以元组形式)。如果字典为空,则引发 KeyError。(在 Python 3.7 之前,移除的是任意一对)。
dict.setdefault(key[, default])如果字典中存在 key,返回其值。如果不存在,则插入 key,并将其值设置为 default(默认为 None),然后返回 default。
dict.update([other])用 other(另一个字典或键值对的可迭代对象)中的键值对更新字典,覆盖现有键。

检查键是否存在于字典中的首选方法是使用 in 运算符:

student = {'name': 'Zara', 'age': 18}
if 'age' in student:
print("Age key exists.")
if 'grade' not in student:
print("Grade key does not exist.")

注意:Python 2 中使用的 dict.has_key(key) 方法在 Python 3 中已被弃用并移除。请改用 in 运算符。

类似于列表推导式,您也可以简洁地创建字典:

squares = {x: x*x for x in range(1, 6)}
# squares will be: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print(squares)