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

相关推荐
独行soc2 分钟前
2025年常见渗透测试面试题- 常见中间件(题目+回答)
前端·python·安全·中间件·面试·xss·红蓝攻防
studyer_domi19 分钟前
Matlab 直流和交流电机PI控制和GUI界面
开发语言·matlab
图梓灵24 分钟前
解析Java根基:Object类核心方法
java·开发语言·jvm
被AI抢饭碗的人24 分钟前
c++11新内容补充
开发语言·c++
爱分享的淘金达人25 分钟前
25年河南事业单位报名详细流程图解
java·python·小程序·tomcat·流程图
User_芊芊君子30 分钟前
【Java实战】——手撕斐波那契数列
java·开发语言
studyer_domi42 分钟前
Matlab 三维时频图
开发语言·人工智能·matlab
小白—人工智能1 小时前
数据可视化 —— 多边图应用(大全)
python·信息可视化·数据可视化
莫魂魂1 小时前
014_多线程
java·开发语言
noravinsc1 小时前
使用django实现windows任务调度管理
python·django·sqlite