字典或者列表常用方法介绍
列表变成字典的方法:
#使用字典推导式d={k:v for k,v in enumerate(nums)}#{0: 2, 1: 11, 2: 7, 3: 15, 4: 26, 5: 12, 6: 6, 7: 9}#使用 enumerate()(索引作键)d=dict(enumerate(nums,start=1))#{1: 2, 2: 11, 3: 7, 4: 15, 5: 26, 6: 12, 7: 6, 8: 9}##使用字典推导式d={m:1 for m in nums}#{2: 1, 11: 1, 7: 1, 15: 1, 26: 1, 12: 1, 6: 1, 9: 1}
enumerate()
enumerate() 用于在循环中同时获取索引和值。
# 基本语法:enumerate(iterable, start=0)
fruits = ['apple', 'banana', 'orange']# 不使用 enumerate
for i in range(len(fruits)):print(f"索引 {i}: {fruits[i]}")# 使用 enumerate(更优雅)
for index, fruit in enumerate(fruits):print(f"索引 {index}: {fruit}")
输出:
索引 0: apple
索引 1: banana
索引 2: orange
从1开始计数
for index, fruit in enumerate(fruits, start=1):
dict.get() 方法
get() 方法用于安全地获取字典中的值,避免 KeyError
# 基本语法:dict.get(key, default=None)
student = {'name': 'Alice', 'age': 20, 'city': 'Beijing'}# 传统方法(可能报错)
# score = student['score'] # KeyError: 'score'# 使用 get() 方法(安全)
score = student.get('score')
print(score) # None# 指定默认值
score = student.get('score', 0)
print(score) # 0# 存在的键正常返回
name = student.get('name', 'Unknown')
print(name) # Alice
字典推导式
{key: value for 循环变量 in 可迭代对象}
即:
{key_expression: value_expression for item in iterable}
字典推导式的完整语法包含可选的条件过滤:
{key_expression: value_expression for item in iterable if condition}
# 创建数字平方的字典
squares = {x: x*x for x in range(1, 6)}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}# 等价的传统写法
squares = {}
for x in range(1, 6):squares[x] = x * x
# 列表转字典
fruits = ['apple', 'banana', 'orange']
fruit_dict = {i: fruit for i, fruit in enumerate(fruits)}
print(fruit_dict) # {0: 'apple', 1: 'banana', 2: 'orange'}# 字符串处理
words = ['hello', 'world', 'python']
length_dict = {word: len(word) for word in words}
print(length_dict) # {'hello': 5, 'world': 5, 'python': 6}
带条件过滤
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]# 只保留偶数
even_squares = {x: x*x for x in numbers if x % 2 == 0}
print(even_squares) # {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}# 多重条件
filtered = {x: x**3 for x in numbers if x > 3 and x < 8}
print(filtered) # {4: 64, 5: 125, 6: 216, 7: 343}
# 键和值都进行转换
original_dict = {'a': 1, 'b': 2, 'c': 3}
# 交换键值对
swapped = {v: k for k, v in original_dict.items()}
print(swapped) # {1: 'a', 2: 'b', 3: 'c'}
# 处理元组列表
students = [('Alice', 85), ('Bob', 92), ('Charlie', 78)]
grade_dict = {name: score for name, score in students}
print(grade_dict) # {'Alice': 85, 'Bob': 92, 'Charlie': 78}
总结
字典推导式的优点:
代码简洁、可读性好
执行效率通常比传统循环高
函数式编程风格
适用场景:
简单的数据转换和过滤
从其他数据结构创建字典
字典的批量更新和转换
items函数介绍
items() 是处理字典时最常用、最强大的方法之一!
dict.items() 返回一个视图对象,包含字典的所有键值对。
person = {'name': 'Alice', 'age': 25, 'city': 'Beijing'}# 获取items视图
items_view = person.items()
print(items_view) # dict_items([('name', 'Alice'), ('age', 25), ('city', 'Beijing')])# 在循环中使用
for key, value in person.items():print(f"{key}: {value}")# 输出:
# name: Alice
# age: 25
# city: Beijing
person = {'name': 'Alice', 'age': 25}
items_view = person.items()
print(list(items_view)) # [('name', 'Alice'), ('age', 25)]# 修改原字典
person['city'] = 'Beijing' # 添加新键值对
person['age'] = 26 # 修改值# 视图对象会自动更新
print(list(items_view)) # [('name', 'Alice'), ('age', 26), ('city', 'Beijing')]
转换为列表
person = {'name': 'Alice', 'age': 25, 'city': 'Beijing'}# 转换为元组列表
items_list = list(person.items())
print(items_list) # [('name', 'Alice'), ('age', 25), ('city', 'Beijing')]# 转换为字典列表(每个键值对作为一个字典)
dict_list = [{k: v} for k, v in person.items()]
print(dict_list) # [{'name': 'Alice'}, {'age': 25}, {'city': 'Beijing'}]
条件过滤
scores = {'math': 85, 'english': 92, 'science': 78, 'history': 65}# 找出高分科目(>=80)
high_scores = {subject: score for subject, score in scores.items() if score >= 80}
print(high_scores) # {'math': 85, 'english': 92}# 找出需要改进的科目
need_improvement = [(subject, score) for subject, score in scores.items() if score < 70]
print(need_improvement) # [('history', 65)]
与其他方法的对比
items() vs keys() vs values()
person = {'name': 'Alice', 'age': 25, 'city': 'Beijing'}print("items():", list(person.items())) # 键值对
print("keys():", list(person.keys())) # 只有键
print("values():", list(person.values())) # 只有值# 输出:
# items(): [('name', 'Alice'), ('age', 25), ('city', 'Beijing')]
# keys(): ['name', 'age', 'city']
# values(): ['Alice', 25, 'Beijing']
字典合并与更新
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}# 合并字典(Python 3.9+ 有更简单的方法)
merged = {k: v for d in [dict1, dict2] for k, v in d.items()}
print(merged) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}# 更新值(基于条件)
scores = {'math': 85, 'english': 92, 'science': 78}
adjusted = {subject: score+5 if score < 90 else score for subject, score in scores.items()}
print(adjusted) # {'math': 90, 'english': 92, 'science': 83}
