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

Python如何按key值匹配搜索字典并为JSON追加对应字段

问题原因

你当前的报错直接来源于赋值逻辑的运算符错误:
wInList['price'] == word['price'] 中使用的==是比较运算符,作用是判断左右两侧的值是否相等,不会给字段赋值。同时因为fruitsnoprice.json的条目本身没有price字段,访问wInList['price']时会直接触发KeyError报错。

修复方案

首先把该行的==替换为赋值运算符=即可解决当前报错,同时可以优化匹配逻辑提升执行效率,完整可运行代码如下:

import json

def add_price(price_json_path, noprice_json_path, output_json_path=None):
    # 先读取带价格的水果数据,构造{水果名: 价格}的映射字典,只需遍历一次
    with open(price_json_path, "r", encoding="utf-8") as f:
        fruit_price_list = json.load(f)
    fruit_price_map = {item["fruit"]: item["price"] for item in fruit_price_list}
    
    # 读取无价格的水果数据
    with open(noprice_json_path, "r", encoding="utf-8-sig") as f:
        noprice_fruit_list = json.load(f)
    
    # 遍历匹配追加price字段
    result = []
    for fruit_item in noprice_fruit_list:
        fruit_name = fruit_item["fruit"]
        if fruit_name in fruit_price_map:
            # 匹配到则追加价格字段
            fruit_item["price"] = fruit_price_map[fruit_name]
            # 若只需要保留匹配成功的条目,把append操作移到这个缩进块内即可
        result.append(fruit_item)
    
    # 打印结果
    print(result)
    
    # 如果需要输出到新的JSON文件可以打开下面的注释
    # if output_json_path:
    #     with open(output_json_path, "w", encoding="utf-8") as f:
    #         json.dump(result, f, ensure_ascii=False, indent=2)

# 调用示例,把文件路径替换成你本地的实际路径
add_price(
    price_json_path="../../dictionary/original.json",
    noprice_json_path="../../dictionary/fruitsnoprice.json"
)

额外注意事项

你示例中贴的JSON结构是不规范的,实际存储的JSON文件必须保证键名用双引号包裹,且最后一个键值对后不能有多余的逗号,否则json.load会解析失败,合法的JSON示例如下:

{
  "fruit": "banana",
  "color": "yellow",
  "price": 20
}

内容的提问来源于stack exchange,提问作者João Pedro

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 16:36:03