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

相关推荐
Java Fans1 分钟前
在WPF项目中集成Python:Python.NET深度实战指南
python·.net·wpf
Cyanto4 分钟前
Java并发编程面试题
java·开发语言·面试
海的诗篇_10 分钟前
前端开发面试题总结-JavaScript篇(一)
开发语言·前端·javascript·学习·面试
じ☆ve 清风°20 分钟前
理解JavaScript中map和parseInt的陷阱:一个常见的面试题解析
开发语言·javascript·ecmascript
豌豆花下猫22 分钟前
Python 潮流周刊#105:Dify突破10万星、2025全栈开发的最佳实践
后端·python·ai
sss191s32 分钟前
Java 集合面试题从数据结构到 HashMap 源码剖析详解及常见考点梳理
java·开发语言·数据结构
嘻嘻哈哈OK啦35 分钟前
day46打卡
python
IGP937 分钟前
20250606-C#知识:委托和事件
开发语言·c#
木头左39 分钟前
Docker容器化技术概述与实践
python
hjyowl1 小时前
题解:AT_abc407_c [ABC407C] Security 2
c语言·开发语言·算法