如何按指定条件更新Python字典中的对应值?
完整实现代码
# 原始字典 origin_dict = { 'A1': [3, 2, 1], 'A2': [9, 10, 11, 12, 13, 14], 'B1': [4, 5, 6, 7, 8], 'B2': [15] } target = 9 # 1. 定位包含target的键,取对应列表最后一个元素 target_key = None for key, val_list in origin_dict.items(): if target in val_list: target_key = key break last_val = origin_dict[target_key][-1] # 2. 遍历其余键修改符合条件的元素 for key, val_list in origin_dict.items(): if key == target_key: continue for idx, item in enumerate(val_list): if item >= target: val_list[idx] = f'After {last_val}' # 输出结果验证 print(origin_dict)
逻辑说明
- 首先遍历字典所有键值对,匹配到包含指定数值9的键
A2,取出该键对应列表的末尾元素14 - 二次遍历字典,跳过
A2对应的键值对,对剩余每个列表的元素逐一判断:元素小于9时不做修改,元素大于等于9时替换为After 14字符串 - 若需要保留原始字典不被修改,可以引入
copy模块做深拷贝后再操作,避免原始数据被改动
内容的提问来源于stack exchange,提问作者royalewithcheese
相关产品推荐
相关产品推荐

