如何搜索字典并通过键值将字段附加到JSON ?



我正在尝试用Python编写这样的脚本:

假设我有两个JSON文件,其中一个的数据结构是这样的:

fruitswithprice.json

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

另一个是fruitsnoprice.json

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

我想将price字段附加到fruitsnoprice。Json格式的每个条目的关键字"水果"。比赛。

我试过了:

new_dict = []

def add_price(json_file):
with open("../../dictionary/original.json", "r", encoding="utf-8") as original_dictionary, open(json_file, "r", encoding="utf-8-sig") as word_list:
dictionary = json.load(original_dictionary)
list_to_append = json.load(word_list)

for word in dictionary:
for wInList in list_to_append:
if word['fruit'] == wInList['fruit']:
wInList['price'] == word['price']
new_dict.append(wInList)
print(new_dict)

在wInList['price'] == word['price']出现错误。

你不能这样做:wInList['price'] == word['price'].

你可以这样赋值:

wInList['price'] = word['price'] # Notice! Just one '='

最新更新