Reputation: 125
with open('example.json', 'r+') as file:
dict_data = json.load(file)
for data in dict_data:
if "field1" in data:
data["field1"] = constants.FIELD1[data["field1"][0]]
if "field2" in data:
data["field2"] = data["field1"] + data[["field2"][0]]
data["field2"] = constants.FIELD2[data["field1"][0]]
I want that data["field1"]
to take the original value and not the value that returns in the previous line. I have changed the execution of the lines but it gives me an error.
Upvotes: 2
Views: 558
Reputation: 50190
I think you mean something like this:
if "field1" in data:
saved_key = data["field1"][0]
data["field1"] = constants.FIELD1[data["field1"][0]]
if "field2" in data:
data["field2"] = data["field1"] + data[["field2"][0]]
data["field2"] = constants.FIELD2[saved_key]
The second block of code only makes sense if both keys exist, so it is embedded under the first if
.
Upvotes: 2