Python案例如何遍历字典键值?

wen python案例 9

本文目录导读:

Python案例如何遍历字典键值?

  1. 使用 .items() 方法(推荐)
  2. 只遍历键
  3. 只遍历值
  4. 遍历并获取索引
  5. 遍历嵌套字典
  6. 条件筛选遍历
  7. 使用字典推导式
  8. 完整示例代码
  9. 性能对比
  10. 注意事项

在 Python 中遍历字典的键值对有多种方式,下面详细介绍几种常见方法:

使用 .items() 方法(推荐)

这是最常用、最Pythonic的方式,可以同时获取键和值:

my_dict = {'name': 'Alice', 'age': 25, 'city': 'Beijing'}
# 遍历键值对
for key, value in my_dict.items():
    print(f"{key}: {value}")
# 输出:
# name: Alice
# age: 25
# city: Beijing

只遍历键

my_dict = {'name': 'Alice', 'age': 25, 'city': 'Beijing'}
# 方法1:直接遍历
for key in my_dict:
    print(key)
# 方法2:使用 .keys() 方法
for key in my_dict.keys():
    print(key)

只遍历值

my_dict = {'name': 'Alice', 'age': 25, 'city': 'Beijing'}
for value in my_dict.values():
    print(value)

遍历并获取索引

使用 enumerate() 获取序号:

my_dict = {'name': 'Alice', 'age': 25, 'city': 'Beijing'}
for index, (key, value) in enumerate(my_dict.items()):
    print(f"索引{index}: {key} -> {value}")
# 输出:
# 索引0: name -> Alice
# 索引1: age -> 25
# 索引2: city -> Beijing

遍历嵌套字典

nested_dict = {
    'person1': {'name': 'Alice', 'age': 25},
    'person2': {'name': 'Bob', 'age': 30}
}
for outer_key, inner_dict in nested_dict.items():
    print(f"外层键: {outer_key}")
    for inner_key, inner_value in inner_dict.items():
        print(f"  {inner_key}: {inner_value}")

条件筛选遍历

my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# 只输出值为偶数的键值对
for key, value in my_dict.items():
    if value % 2 == 0:
        print(f"{key}: {value}")  # 输出: b: 2, d: 4

使用字典推导式

my_dict = {'a': 1, 'b': 2, 'c': 3}
# 反转键值对
reversed_dict = {value: key for key, value in my_dict.items()}
print(reversed_dict)  # 输出: {1: 'a', 2: 'b', 3: 'c'}

完整示例代码

# 综合示例
def demonstrate_dict_traversal():
    # 学生成绩字典
    scores = {
        '张三': 85,
        '李四': 92,
        '王五': 78,
        '赵六': 95
    }
    print("=== 遍历所有学生成绩 ===")
    for name, score in scores.items():
        print(f"{name}: {score}分")
    print("\n=== 找出优秀学生(90分以上)===")
    excellent_students = []
    for name, score in scores.items():
        if score >= 90:
            excellent_students.append(name)
            print(f"恭喜 {name},成绩优秀!")
    print(f"\n优秀学生名单: {excellent_students}")
    print("\n=== 计算平均分 ===")
    total_score = 0
    for score in scores.values():
        total_score += score
    average = total_score / len(scores)
    print(f"班级平均分: {average:.1f}分")
# 运行示例
demonstrate_dict_traversal()

性能对比

  • .items():最常用,内存效率好
  • 直接遍历字典:等同于 .keys()
  • .keys().values():视图对象,节省内存

注意事项

  1. Python 3.x 中,dict.items(), dict.keys(), dict.values() 返回的是视图对象,不是列表
  2. 遍历时不要修改字典大小(添加或删除键),否则会引发 RuntimeError
  3. 需要安全删除元素时,建议先复制键列表
# 安全删除示例
my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# 错误的做法(会报错)
# for key in my_dict:
#     if my_dict[key] < 3:
#         del my_dict[key]
# 正确的做法
for key in list(my_dict.keys()):
    if my_dict[key] < 3:
        del my_dict[key]
print(my_dict)  # 输出: {'c': 3, 'd': 4}

最推荐使用 for key, value in dict.items(): 这种写法,既清晰又高效。

抱歉,评论功能暂时关闭!