I am trying to write a script like this in Python:
Let’s say I have two JSON files, one has a data structure like this :
fruitswithprice.json
JavaScript
x
6
1
{
2
fruit: "banana",
3
color: "yellow",
4
price : 20,
5
}
6
the other is fruitsnoprice.json
JavaScript
1
5
1
{
2
fruit: "banana",
3
color: "yellow",
4
}
5
I want to append the price field to fruitsnoprice.json for every entry that the key “fruit” matches.
I tried this :
JavaScript
1
15
15
1
new_dict = []
2
3
4
def add_price(json_file):
5
with open("../../dictionary/original.json", "r", encoding="utf-8") as original_dictionary, open(json_file, "r", encoding="utf-8-sig") as word_list:
6
dictionary = json.load(original_dictionary)
7
list_to_append = json.load(word_list)
8
9
for word in dictionary:
10
for wInList in list_to_append:
11
if word['fruit'] == wInList['fruit']:
12
wInList['price'] == word['price']
13
new_dict.append(wInList)
14
print(new_dict)
15
getting an error at wInList[‘price’] == word[‘price’].
Advertisement
Answer
You can’t do this: wInList['price'] == word['price']
.
You can assign it like this:
JavaScript
1
2
1
wInList['price'] = word['price'] # Notice! Just one '='
2