You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按指定条件更新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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 10:57:03