Python开发——Python 字典的使用

1. 字典的基本操作

1.1 创建字典

# 使用花括号创建字典
dict1 = {'key1': 'value1', 'key2': 'value2'}

# 使用dict()函数创建字典
dict2 = dict(key1='value1', key2='value2')

1.2 访问字典的值

# 使用键访问值
print(dict1['key1'])  # 输出:value1

# 使用get()方法访问值
print(dict1.get('key1'))  # 输出:value1

2. `get()` 方法

2.1 基本用法

dict1 = {'key1': 'value1', 'key2': 'value2'}
print(dict1.get('key1'))  # 输出:value1
print(dict1.get('key3'))  # 输出:None

2.2 设置默认返回值

print(dict1.get('key3', '默认值'))  # 输出:默认值

2.3 不同类型的默认返回值

print(dict1.get('key3', 1))       # 输出:1
print(dict1.get('key3', 1.1))     # 输出:1.1
print(dict1.get('key3', True))    # 输出:True
print(dict1.get('key3', [1, 2]))  # 输出:[1, 2]
print(dict1.get('key3', (1, 2)))  # 输出:(1, 2)
print(dict1.get('key3', {1, 2}))  # 输出:{1, 2}

3. 嵌套字典取值

3.1 基本用法

dict1 = {'key1': 'value1', 'key2': {'key3': 'value3'}}
print(dict1.get('key2').get('key3'))  # 输出:value3

3.2 分步取值

result = dict1.get('key2')
print(result)  # 输出:{'key3': 'value3'}
result1 = result.get('key3')
print(result1)  # 输出:value3

4. 字典的常见操作

4.1 添加和修改字典项

dict1['key3'] = 'value3'  # 添加新项
dict1['key1'] = 'new_value1'  # 修改现有项
print(dict1)  # 输出:{'key1': 'new_value1', 'key2': 'value2', 'key3': 'value3'}

4.2 删除字典项

del dict1['key1']  # 删除键为'key1'的项
print(dict1)  # 输出:{'key2': 'value2', 'key3': 'value3'}

# 使用pop()方法删除并返回该项的值
value = dict1.pop('key2')
print(value)  # 输出:value2
print(dict1)  # 输出:{'key3': 'value3'}

4.3 遍历字典

for key, value in dict1.items():
    print(f'{key}: {value}')

5. 字典的高级操作

5.1 字典的合并

在Python 3.9及以上版本中,可以使用 `|` 运算符合并字典:

dict1 = {'key1': 'value1'}
dict2 = {'key2': 'value2'}
merged_dict = dict1 | dict2
print(merged_dict)  # 输出:{'key1': 'value1', 'key2': 'value2'}

在较低版本中,可以使用 `update()` 方法:

dict1.update(dict2)
print(dict1)  # 输出:{'key1': 'value1', 'key2': 'value2'}

5.2 字典推导式

字典推导式可以用来创建字典:

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

5.3 使用 `defaultdict`

`defaultdict` 是 `collections` 模块中的一个字典子类,它提供了一个默认值给所有不存在的键:

from collections import defaultdict

dd = defaultdict(lambda: '默认值')
dd['key1'] = 'value1'
print(dd['key1'])  # 输出:value1
print(dd['key2'])  # 输出:默认值

5.4 使用 `Counter`

`Counter` 是 `collections` 模块中的一个字典子类,用于计数:

from collections import Counter

data = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
counter = Counter(data)
print(counter)  # 输出:Counter({'apple': 3, 'banana': 2, 'orange': 1})

5.5 有序字典

在Python 3.7及以上版本中,普通字典已经保证插入顺序。但是在较低版本中,可以使用 `OrderedDict`:

from collections import OrderedDict

od = OrderedDict()
od['key1'] = 'value1'
od['key2'] = 'value2'
od['key3'] = 'value3'
for key, value in od.items():
    print(f'{key}: {value}')

6. 字典的实际应用

6.1 统计字符出现次数

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}

6.2 将两个列表合并为字典

keys = ['name', 'age', 'city']
values = ['Alice', 25, 'New York']

person = dict(zip(keys, values))
print(person)  # 输出:{'name': 'Alice', 'age': 25, 'city': 'New York'}

6.3 分组数据

假设你有一组学生成绩数据,想要按班级分组:

students = [
    {'name': 'Alice', 'class': 'A', 'score': 85},
    {'name': 'Bob', 'class': 'B', 'score': 90},
    {'name': 'Charlie', 'class': 'A', 'score': 95},
    {'name': 'David', 'class': 'B', 'score': 80}
]

grouped_data = defaultdict(list)

for student in students:
    grouped_data[student['class']].append(student)

print(dict(grouped_data))
# 输出:
# {
#     'A': [{'name': 'Alice', 'class': 'A', 'score': 85}, {'name': 'Charlie', 'class': 'A', 'score': 95}],
#     'B': [{'name': 'Bob', 'class': 'B', 'score': 90}, {'name': 'David', 'class': 'B', 'score': 80}]
# }

通过这些示例和扩展,希望你能更好地理解和应用Python中的字典。

相关推荐
uppp»3 分钟前
深入理解 Java 反射机制:获取类信息与动态操作
java·开发语言
Yan-英杰5 分钟前
百度搜索和文心智能体接入DeepSeek满血版——AI搜索的新纪元
图像处理·人工智能·python·深度学习·deepseek
weixin_307779131 小时前
Azure上基于OpenAI GPT-4模型验证行政区域数据的设计方案
数据仓库·python·云计算·aws
玩电脑的辣条哥2 小时前
Python如何播放本地音乐并在web页面播放
开发语言·前端·python
多想和从前一样5 小时前
Django 创建表时 “__str__ ”方法的使用
后端·python·django
ll7788115 小时前
LeetCode每日精进:20.有效的括号
c语言·开发语言·算法·leetcode·职场和发展
小喵要摸鱼6 小时前
【Pytorch 库】自定义数据集相关的类
pytorch·python
bdawn6 小时前
深度集成DeepSeek大模型:WebSocket流式聊天实现
python·websocket·openai·api·实时聊天·deepseek大模型·流式输出
Jackson@ML6 小时前
Python数据可视化简介
开发语言·python·数据可视化
mosquito_lover16 小时前
怎么把pyqt界面做的像web一样漂亮
前端·python·pyqt