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中的字典。

相关推荐
Attacking-Coder22 分钟前
前端面试宝典---项目难点2-智能问答对话框采用虚拟列表动态渲染可视区域元素(10万+条数据)
开发语言·前端·javascript
mit6.82427 分钟前
[Nagios Core] 通知系统 | 事件代理 | NEB模块,事件,回调
c语言·开发语言
mit6.82429 分钟前
[Nagios Core] 事件调度 | 检查执行 | 插件与进程
c语言·开发语言·性能优化
惊骇世俗王某人37 分钟前
1. 深入理解ArrayList源码
java·开发语言
今天炼丹了吗1 小时前
RTDETR融合[WACV 2025]SEM-Net中的模块
python·深度学习·机器学习
赤鸢QAQ1 小时前
Qt小组件 - 2(布局)瀑布流布局,GridLayout,FlowLayout
开发语言·数据库·qt
小灰灰搞电子1 小时前
Qt使用dump文件记录并查找软件奔溃信息详细教程
开发语言·qt
这里有鱼汤2 小时前
一篇文章让你彻底搞懂量化中RSI指标,附实战策略+附源码,建议收藏
python
IIIIIII_II2 小时前
【视频格式转换】.264格式转为mp4格式
python·视频·格式转换
都叫我大帅哥2 小时前
LangChain的TXT文档加载:从入门到实战的终极指南
python·langchain