Home > other >  Nested Dictionary - Accesing data summing up values
Nested Dictionary - Accesing data summing up values

Time:10-18

i have a data like this:

js = {"data": [
 {'state': 'Florida',
  'shortname': 'FL',
  'info': {'governor': 'Rick Scott'},
  'counties': [{'name': 'Dade', 'population': '12345'},
               {'name': 'Broward', 'population': '40000'},
               {'name': 'Palm Beach', 'population': '60000'}]},
 {'state': 'Ohio',
  'shortname': 'OH',
  'info': {'governor': 'John Kasich'},
  'counties': [{'name': 'Summit', 'population': '1234'},
               {'name': 'Cuyahoga', 'population': '1337'}]}]

}

The task is to write a program which will print for every state it's population, so the expected output would be:

Florida 22345
Ohio 2571

I have to use json module in this task, but i don't have an idea how. I only just know how to access 'state' but idk how to sum the population

for i in js['data']:
print(i['state'], i['counties'][0]['population']   i['counties'][1]['population']... etc but summing up the population manually is no the proper way i guess..)

CodePudding user response:

Use sum to add together all the population of each county:

# iterate over all records in data
for record in js["data"]:
    # sum the population of each county
    total = sum(county["population"] for county in record["counties"])

    # fetch the name of the state 
    # print it together with the total
    print(record["state"], total)

Output

Florida 22345
Ohio 2571

Refer to this resource for learning more about looping over dictionaries.

UPDATE

If the population are strings, use int to convert to integers before summing:

# sum the population of each county
total = sum(int(county["population"]) for county in record["counties"])

CodePudding user response:

try like this:

for i in js['data']:
    print(i['state'], sum(rec['population'] for rec in i['countries']))
  • Related