字典(Dictionary)是Python中一种非常灵活的数据结构,用于存储键值对(key-value pairs)。在Python中创建字典有多种方法,每种方法都有其特定的使用场景和优势。
本文将详细介绍Python中创建字典的几种常见方法,包括相关知识讲解、代码示例以及实际应用案例。
字典是一种可变容器模型,且可存储任意类型对象,包括数字、字符串、列表、元组、甚至其他字典。
字典的每个键值对用冒号:分隔,每个对之间用逗号,分隔,整个字典包括在花括号{}中。
字典包含如下特点:
1 2 3 4 5 |
# 基本用法 my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
# 空字典 empty_dict = {} |
1 2 3 4 5 6 |
# 从键值对元组列表创建 items = [('name', 'Bob'), ('age', 30), ('city', 'Los Angeles')] my_dict = dict(items)
# 直接使用关键字参数 my_dict = dict(name='Charlie', age=35, city='Chicago') |
1 2 3 |
# 根据列表生成字典 numbers = [1, 2, 3, 4] my_dict = {num: num**2 for num in numbers} |
1 2 3 4 5 6 7 8 9 10 11 12 |
from collections import defaultdict, OrderedDict
# 默认值字典 dd = defaultdict(lambda: 'N/A') dd['key1'] = 'value1' print(dd) # 输出:defaultdict(<function <lambda> at ...>, {'key1': 'value1'})
# 有序字典 od = OrderedDict() od['one'] = 1 od['two'] = 2 od.move_to_end('one') # 将'one'移动到末尾 |
1 2 3 |
dic = {} print(type(dic)) # 输出结果:<class 'dict'> |
1 2 3 |
dic = dict(zip('abc', [1, 2, 3])) print(dic) # 输出结果:{'a': 1, 'b': 2, 'c': 3} |
1 2 3 |
dic = dict.fromkeys(range(4), 'x') print(dic) # 输出结果:{0: 'x', 1: 'x', 2: 'x', 3: 'x'} |
1 2 3 4 5 6 7 8 9 10 11 12 |
# 创建用户信息字典 user_info = { 'username': 'john_doe', 'email': 'john@example.com', 'signup_date': '2024-06-08' }
# 更新用户信息 user_info['email'] = 'new_john@example.com'
# 访问用户信息 print(user_info['username']) |
1 2 3 4 5 6 7 8 9 10 |
# 假设我们有一个包含不完整数据的列表 data = ['name', 'age', 'city', 'name', 'email']
# 使用defaultdict自动填充缺失数据 info = defaultdict(str) for item in data: key, value = item, info[item] if item in info else 'Not provided' info[key] = value
print(info) |
1 2 3 |
# 创建一个字典,其中包含数字及其平方 squares = {x: x**2 for x in range(6)} print(squares) |
字典的键必须是不可变类型,如字符串、数字或元组。
在Python 3.7+中,字典保持插入顺序,但这不是语言规范的一部分,因此依赖此特性可能存在风险。
使用defaultdict和OrderedDict时,需要从collections模块导入。