I have this json file:
[{"industry": "car", "price": 100.0, "earnings": 10.0, "name": "Volvo"},
{"industry": "car", "price": 280.0, "earnings": 11.0, "name": "Audi"},
{"industry": "car", "price": 190.0, "earnings": 7.0, "name": "Ferrari"},
{"industry": "Phone", "price": 90.0, "earnings": 2.0, "name": "Nokia"},
{"industry": "Phone", "price": 200.0, "earnings": 14.0, "name": "Samsung"},
{"industry": "Phone", "price": 40.0, "earnings": 7.0, "name": "Apple"}]
I printed the contents of the object using the method print. I calculated the price to earnings ratio (price/earnings) for each firm
This is my code:
import json
from pprint import pprint
with open('firm_list.json', encoding='utf-8') as data_file:
data = json.loads(data_file.read())
pprint(data)
for item in data:
pe= item['price']/item['earnings']
print(pe)
data.update['price to earnings ratio'] = pe
I want to add price/earnings to the dictionary, but it doesn't work. Can you help me figure out what I'm doing wrong?
CodePudding user response:
Put the adding operation inside the loop
import json
from pprint import pprint
with open('firm_list.json', encoding='utf-8') as data_file:
data = json.loads(data_file.read())
pprint(data)
for item in data:
pe= item['price']/item['earnings']
print(pe)
item['price to earnings ratio'] = pe
CodePudding user response:
Try this one.
import json
from pprint import pprint
with open('firm_list.json', encoding='utf-8') as data_file:
data = json.loads(data_file.read())
pprint(data)
for item in data:
pe = item['price'] / item['earnings']
item['price to earnings ratio'] = pe
print(pe)
pprint(data)
CodePudding user response:
Instead of data.update you just have to use data['price']='new value'