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

相关推荐
杰克尼4 分钟前
蓝桥云课-5. 花灯调整【算法赛】
java·开发语言·算法
.小墨迹5 分钟前
C++学习之std::move 的用法与优缺点分析
linux·开发语言·c++·学习·算法·ubuntu
努力学习的小廉5 分钟前
【QT(五)】—— 常用控件(二)
开发语言·qt
wanghowie6 分钟前
01.02 Java基础篇|核心数据结构速查
java·开发语言·数据结构
|晴 天|11 分钟前
前端闭包:从概念到实战,解锁JavaScript高级技能
开发语言·前端·javascript
骚戴18 分钟前
n1n:从替代LiteLLM Proxy自建网关到企业级统一架构的进阶之路
人工智能·python·大模型·llm·gateway·api
点云SLAM20 分钟前
C++ error C2065: “M_PI”: 未声明的标识符 解决方案
开发语言·c++·error c2065·m_pi未声明 解决方案
秋氘渔21 分钟前
智演沙盘 —— 基于大模型的智能面试评估系统
python·mysql·django·drf
爱笑的眼睛1124 分钟前
超越AdamW:优化器算法的深度实现、演进与自定义框架设计
java·人工智能·python·ai
qq_3363139325 分钟前
java基础-stream流练习
java·开发语言·python