Skip to content

Python 字典

字典是 Python 中的一种无序、可变的数据结构,用于存储键值对。本章节将详细介绍 Python 中的字典及其操作。

字典的创建

可以使用花括号 {}dict() 函数来创建字典。

示例:

python
# 字典的创建

# 使用花括号创建字典
dict1 = {"name": "Alice", "age": 30, "city": "New York"}
print(dict1)  # 输出:{'name': 'Alice', 'age': 30, 'city': 'New York'}

# 创建空字典
dict2 = {}
print(dict2)  # 输出:{}

# 使用 dict() 函数创建字典
dict3 = dict()
print(dict3)  # 输出:{}

# 使用键值对参数创建字典
dict4 = dict(name="Bob", age=25, city="London")
print(dict4)  # 输出:{'name': 'Bob', 'age': 25, 'city': 'London'}

# 使用列表或元组的序列创建字典
dict5 = dict([("name", "Charlie"), ("age", 35), ("city", "Paris")])
print(dict5)  # 输出:{'name': 'Charlie', 'age': 35, 'city': 'Paris'}

# 使用字典推导式创建字典
dict6 = {i: i**2 for i in range(5)}
print(dict6)  # 输出:{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

# 使用 zip() 函数创建字典
keys = ["name", "age", "city"]
values = ["David", 40, "Tokyo"]
dict7 = dict(zip(keys, values))
print(dict7)  # 输出:{'name': 'David', 'age': 40, 'city': 'Tokyo'}

字典的访问

可以使用键来访问字典中的值,也可以使用 get() 方法来访问。

使用键访问

示例:

python
# 使用键访问字典
dict = {"name": "Alice", "age": 30, "city": "New York"}

# 访问存在的键
print(dict["name"])  # 输出:Alice
print(dict["age"])  # 输出:30
print(dict["city"])  # 输出:New York

# 访问不存在的键会引发错误
# print(dict["country"])  # KeyError: 'country'

使用 get() 方法访问

示例:

python
# 使用 get() 方法访问字典
dict = {"name": "Alice", "age": 30, "city": "New York"}

# 访问存在的键
print(dict.get("name"))  # 输出:Alice
print(dict.get("age"))  # 输出:30
print(dict.get("city"))  # 输出:New York

# 访问不存在的键,返回 None
print(dict.get("country"))  # 输出:None

# 访问不存在的键,返回默认值
print(dict.get("country", "USA"))  # 输出:USA

字典的修改

字典是可变的,可以修改字典中的值,添加新的键值对,或删除现有的键值对。

修改值

示例:

python
# 修改字典中的值
dict = {"name": "Alice", "age": 30, "city": "New York"}

# 修改现有的键对应的值
dict["age"] = 31
dict["city"] = "Boston"
print(dict)  # 输出:{'name': 'Alice', 'age': 31, 'city': 'Boston'}

添加新键值对

示例:

python
# 添加新键值对
dict = {"name": "Alice", "age": 30, "city": "New York"}

# 添加新的键值对
dict["country"] = "USA"
dict["job"] = "Engineer"
print(dict)  # 输出:{'name': 'Alice', 'age': 30, 'city': 'New York', 'country': 'USA', 'job': 'Engineer'}

删除键值对

可以使用 del 语句、pop() 方法或 popitem() 方法来删除键值对。

示例:

python
# 删除键值对
dict = {"name": "Alice", "age": 30, "city": "New York", "country": "USA", "job": "Engineer"}

# 使用 del 语句删除
print("使用 del 语句删除 'job' 键:")
del dict["job"]
print(dict)  # 输出:{'name': 'Alice', 'age': 30, 'city': 'New York', 'country': 'USA'}

# 使用 pop() 方法删除(返回被删除的值)
print("\n使用 pop() 方法删除 'country' 键:")
country = dict.pop("country")
print(f"被删除的值:{country}")  # 输出:被删除的值:USA
print(dict)  # 输出:{'name': 'Alice', 'age': 30, 'city': 'New York'}

# 使用 pop() 方法删除不存在的键,返回默认值
print("\n使用 pop() 方法删除不存在的键:")
job = dict.pop("job", "Unknown")
print(f"被删除的值(默认):{job}")  # 输出:被删除的值(默认):Unknown
print(dict)  # 输出:{'name': 'Alice', 'age': 30, 'city': 'New York'}

# 使用 popitem() 方法删除(返回最后添加的键值对)
print("\n使用 popitem() 方法删除:")
item = dict.popitem()
print(f"被删除的键值对:{item}")  # 输出:被删除的键值对:('city', 'New York')
print(dict)  # 输出:{'name': 'Alice', 'age': 30}

# 清空字典
dict.clear()
print("\n清空字典后:")
print(dict)  # 输出:{}

字典的方法

Python 提供了许多内置的字典方法,用于操作字典。

键、值和项的获取

方法描述示例
keys()返回字典中所有键的视图dict.keys()
values()返回字典中所有值的视图dict.values()
items()返回字典中所有键值对的视图dict.items()

示例:

python
# 键、值和项的获取
dict = {"name": "Alice", "age": 30, "city": "New York"}

# keys() 方法
print("字典的键:")
keys = dict.keys()
print(keys)  # 输出:dict_keys(['name', 'age', 'city'])
print(list(keys))  # 转换为列表,输出:['name', 'age', 'city']

# values() 方法
print("\n字典的值:")
values = dict.values()
print(values)  # 输出:dict_values(['Alice', 30, 'New York'])
print(list(values))  # 转换为列表,输出:['Alice', 30, 'New York']

# items() 方法
print("\n字典的键值对:")
items = dict.items()
print(items)  # 输出:dict_items([('name', 'Alice'), ('age', 30), ('city', 'New York')])
print(list(items))  # 转换为列表,输出:[('name', 'Alice'), ('age', 30), ('city', 'New York')]

字典的更新

方法描述示例
update(other)使用另一个字典或可迭代对象更新字典dict.update({"age": 31, "country": "USA"})
setdefault(key, default)如果键不存在,设置默认值并返回;如果键存在,返回现有值dict.setdefault("country", "USA")

示例:

python
# 字典的更新
dict = {"name": "Alice", "age": 30, "city": "New York"}

# update() 方法
print("使用 update() 方法更新字典:")
dict.update({"age": 31, "country": "USA"})
print(dict)  # 输出:{'name': 'Alice', 'age': 31, 'city': 'New York', 'country': 'USA'}

# 使用关键字参数更新
dict.update(job="Engineer")
print(dict)  # 输出:{'name': 'Alice', 'age': 31, 'city': 'New York', 'country': 'USA', 'job': 'Engineer'}

# setdefault() 方法
print("\n使用 setdefault() 方法:")
# 键不存在,设置默认值并返回
country = dict.setdefault("country", "Canada")
print(f"country 值:{country}")  # 输出:country 值:USA(键已存在,返回现有值)

# 键不存在,设置默认值并返回
zip_code = dict.setdefault("zip_code", "10001")
print(f"zip_code 值:{zip_code}")  # 输出:zip_code 值:10001
print(dict)  # 输出:{'name': 'Alice', 'age': 31, 'city': 'New York', 'country': 'USA', 'job': 'Engineer', 'zip_code': '10001'}

字典的拷贝

方法描述示例
copy()返回字典的浅拷贝dict.copy()
dict(dict)使用构造函数创建字典的浅拷贝dict(dict)

示例:

python
# 字典的拷贝
dict = {"name": "Alice", "age": 30, "city": "New York"}

# copy() 方法
print("使用 copy() 方法创建拷贝:")
dict_copy = dict.copy()
print(dict_copy)  # 输出:{'name': 'Alice', 'age': 30, 'city': 'New York'}

# 修改原字典,不影响拷贝
dict["age"] = 31
print(f"原字典:{dict}")  # 输出:原字典:{'name': 'Alice', 'age': 31, 'city': 'New York'}
print(f"拷贝字典:{dict_copy}")  # 输出:拷贝字典:{'name': 'Alice', 'age': 30, 'city': 'New York'}

# 使用构造函数创建拷贝
dict_copy2 = dict(dict)
print("\n使用构造函数创建拷贝:")
print(dict_copy2)  # 输出:{'name': 'Alice', 'age': 31, 'city': 'New York'}

其他方法

方法描述示例
clear()清空字典dict.clear()
in检查键是否在字典中"name" in dict
not in检查键是否不在字典中"country" not in dict
len(dict)返回字典的长度(键值对的数量)len(dict)

示例:

python
# 其他方法
dict = {"name": "Alice", "age": 30, "city": "New York"}

# len() 函数
print(f"字典的长度:{len(dict)}")  # 输出:字典的长度:3

# in 运算符
print(f"'name' 在字典中:{'name' in dict}")  # 输出:'name' 在字典中:True
print(f"'country' 在字典中:{'country' in dict}")  # 输出:'country' 在字典中:False

# not in 运算符
print(f"'country' 不在字典中:{'country' not in dict}")  # 输出:'country' 不在字典中:True

# clear() 方法
print("\n使用 clear() 方法清空字典:")
dict.clear()
print(f"清空后的字典:{dict}")  # 输出:清空后的字典:{}
print(f"清空后的字典长度:{len(dict)}")  # 输出:清空后的字典长度:0

字典的遍历

可以使用 for 循环来遍历字典中的键、值或键值对。

示例:

python
# 字典的遍历
dict = {"name": "Alice", "age": 30, "city": "New York"}

# 遍历键
print("遍历键:")
for key in dict:
    print(key)

# 或者明确使用 keys() 方法
print("\n使用 keys() 方法遍历键:")
for key in dict.keys():
    print(key)

# 遍历值
print("\n遍历值:")
for value in dict.values():
    print(value)

# 遍历键值对
print("\n遍历键值对:")
for key, value in dict.items():
    print(f"{key}: {value}")

# 遍历键值对(使用元组拆包)
print("\n使用元组拆包遍历键值对:")
for item in dict.items():
    key, value = item
    print(f"{key}: {value}")

字典推导式

字典推导式是一种简洁的创建字典的方法,语法为 {key_expression: value_expression for item in iterable if condition}

示例:

python
# 字典推导式

# 创建一个包含 0 到 9 的平方的字典
print("创建平方字典:")
squares = {i: i**2 for i in range(10)}
print(squares)  # 输出:{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

# 创建一个包含偶数的平方的字典
print("\n创建偶数平方字典:")
even_squares = {i: i**2 for i in range(10) if i % 2 == 0}
print(even_squares)  # 输出:{0: 0, 2: 4, 4: 16, 6: 36, 8: 64}

# 转换字典的值
print("\n转换字典的值:")
dict = {"a": 1, "b": 2, "c": 3}
dict_upper = {key.upper(): value * 2 for key, value in dict.items()}
print(dict_upper)  # 输出:{'A': 2, 'B': 4, 'C': 6}

# 合并两个字典
print("\n合并两个字典:")
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
merged_dict = {**dict1, **dict2}
print(merged_dict)  # 输出:{'a': 1, 'b': 2, 'c': 3, 'd': 4}

# 或者使用字典推导式合并
merged_dict2 = {k: v for d in [dict1, dict2] for k, v in d.items()}
print(merged_dict2)  # 输出:{'a': 1, 'b': 2, 'c': 3, 'd': 4}

字典的嵌套

字典可以嵌套,即一个字典中可以包含其他字典。

示例:

python
# 字典的嵌套

# 创建嵌套字典
person = {
    "name": "Alice",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "New York",
        "country": "USA"
    },
    "contacts": {
        "email": "alice@example.com",
        "phone": "123-456-7890"
    }
}

print(person)  # 输出:{'name': 'Alice', 'age': 30, 'address': {'street': '123 Main St', 'city': 'New York', 'country': 'USA'}, 'contacts': {'email': 'alice@example.com', 'phone': '123-456-7890'}}

# 访问嵌套字典中的元素
print(f"姓名:{person['name']}")  # 输出:姓名:Alice
print(f"城市:{person['address']['city']}")  # 输出:城市:New York
print(f"邮箱:{person['contacts']['email']}")  # 输出:邮箱:alice@example.com

# 修改嵌套字典中的元素
person['address']['city'] = "Boston"
person['contacts']['phone'] = "987-654-3210"
print("\n修改后的嵌套字典:")
print(person)  # 输出:{'name': 'Alice', 'age': 30, 'address': {'street': '123 Main St', 'city': 'Boston', 'country': 'USA'}, 'contacts': {'email': 'alice@example.com', 'phone': '987-654-3210'}}

# 遍历嵌套字典
print("\n遍历嵌套字典:")
for key, value in person.items():
    if isinstance(value, dict):
        print(f"{key}:")
        for sub_key, sub_value in value.items():
            print(f"  {sub_key}: {sub_value}")
    else:
        print(f"{key}: {value}")

字典的深浅拷贝

浅拷贝

浅拷贝创建一个新字典,但字典中的值仍然是原字典中值的引用。

示例:

python
# 浅拷贝
dict1 = {"name": "Alice", "age": 30, "address": {"city": "New York"}}
dict2 = dict1.copy()

# 修改原字典中的不可变值
dict1["age"] = 31
print(dict1)  # 输出:{'name': 'Alice', 'age': 31, 'address': {'city': 'New York'}}
print(dict2)  # 输出:{'name': 'Alice', 'age': 30, 'address': {'city': 'New York'}}(不受影响)

# 修改原字典中的可变值
dict1["address"]["city"] = "Boston"
print(dict1)  # 输出:{'name': 'Alice', 'age': 31, 'address': {'city': 'Boston'}}
print(dict2)  # 输出:{'name': 'Alice', 'age': 30, 'address': {'city': 'Boston'}}(受影响)

深拷贝

深拷贝创建一个新字典,并且递归地拷贝字典中的所有值。

示例:

python
# 深拷贝
import copy

dict1 = {"name": "Alice", "age": 30, "address": {"city": "New York"}}
dict2 = copy.deepcopy(dict1)

# 修改原字典中的不可变值
dict1["age"] = 31
print(dict1)  # 输出:{'name': 'Alice', 'age': 31, 'address': {'city': 'New York'}}
print(dict2)  # 输出:{'name': 'Alice', 'age': 30, 'address': {'city': 'New York'}}(不受影响)

# 修改原字典中的可变值
dict1["address"]["city"] = "Boston"
print(dict1)  # 输出:{'name': 'Alice', 'age': 31, 'address': {'city': 'Boston'}}
print(dict2)  # 输出:{'name': 'Alice', 'age': 30, 'address': {'city': 'New York'}}(不受影响)

字典的应用场景

字典的键值对结构使其在以下场景中特别有用:

  1. 存储相关数据:当需要存储相关联的数据时,使用字典可以通过键快速访问值。
  2. 计数:使用字典可以方便地统计元素出现的次数。
  3. 映射:字典可以作为一种映射关系,将一个值映射到另一个值。
  4. 配置信息:使用字典可以存储和管理配置信息。
  5. 缓存:字典可以作为简单的缓存,存储计算结果或其他需要快速访问的数据。

示例:

python
# 字典的应用场景

# 计数
print("使用字典计数:")
text = "hello world"
char_count = {}
for char in text:
    if char in char_count:
        char_count[char] += 1
    else:
        char_count[char] = 1
print(char_count)  # 输出:{'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}

# 使用 collections.Counter 更简洁
from collections import Counter
char_count2 = Counter(text)
print(char_count2)  # 输出:Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})

# 映射
print("\n使用字典映射:")
month_numbers = {
    "January": 1,
    "February": 2,
    "March": 3,
    "April": 4,
    "May": 5,
    "June": 6,
    "July": 7,
    "August": 8,
    "September": 9,
    "October": 10,
    "November": 11,
    "December": 12
}
print(f"March 的月份数字:{month_numbers['March']}")  # 输出:March 的月份数字:3

# 配置信息
print("\n使用字典存储配置信息:")
config = {
    "database": {
        "host": "localhost",
        "port": 5432,
        "name": "mydb",
        "user": "admin",
        "password": "password"
    },
    "server": {
        "host": "0.0.0.0",
        "port": 8080,
        "debug": True
    }
}
print(f"数据库主机:{config['database']['host']}")  # 输出:数据库主机:localhost
print(f"服务器端口:{config['server']['port']}")  # 输出:服务器端口:8080

# 缓存
print("\n使用字典作为缓存:")
def expensive_function(n):
    print(f"计算 {n} 的平方...")
    return n * n

cache = {}
def get_cached_result(n):
    if n in cache:
        print(f"从缓存中获取 {n} 的结果...")
        return cache[n]
    else:
        result = expensive_function(n)
        cache[n] = result
        return result

print(get_cached_result(5))  # 输出:计算 5 的平方... 25
print(get_cached_result(5))  # 输出:从缓存中获取 5 的结果... 25
print(get_cached_result(10))  # 输出:计算 10 的平方... 100
print(get_cached_result(10))  # 输出:从缓存中获取 10 的结果... 100

总结

Python 中的字典是一种非常灵活的数据结构,提供了丰富的方法来操作键值对。本章节介绍了字典的创建、访问、修改、方法、遍历、推导式、嵌套、拷贝和应用场景等内容。掌握字典的使用对于编写 Python 代码非常重要。