Home > other >  How do I add numbers from multiple for loops in python?
How do I add numbers from multiple for loops in python?

Time:03-16

helpp.json

{
"States":{
    "Illinois":{
        "county":[
            {
             "population":100000,
             "nameofcounty":"Dupage"   
            },
            {
                "population":200000,
                "nameofcounty":"Marion"   
               }
        ]
    },
    "Indiana":{
        "county":[
            {
             "population":100000,
             "nameofcounty":"Dupage"   
            },
            {
                "population":200000,
                "nameofcounty":"Marion"   
               }
        ]
    }
}
}

mycode

import json

with open('helpp.json') as file: 
    package_json = json.load(file)
IN = package_json['States']['Illinois']['county']
IL = package_json['States']['Indiana']['county']

for i in IN:
    county = i['nameofcounty']
    population = i['population']
for j in IL:
    population = j['population']
    county = j['nameofcounty']

    total_population = i['population'] j['population']
    print(county,total_population)

I cant figure out how to add numbers from multiple for loops correctly. my current output is Dupage 300000 Marion 400000 but its suppose to be Dupage 200000 Marion 400000.

CodePudding user response:

The simple error which you are doing in your code is the second last line wherein you are adding i['population'] with j['population'. Herein, the first for loop has been exited so the code takes the last value of i to be 200000 (population of Marion). Thus, to prevent this error you can firstly have different names because I don't really know why would you define population 2 different times for 2 different datasets with the same variable. Here are some of the ways you can go through it:

import json
with open('test.json') as file: 
    package_json = json.load(file)
IN = package_json['States']['Illinois']['county']
IL = package_json['States']['Indiana']['county']

for i in IN:
    county = i['nameofcounty']
    population = i['population']
    for j in IL:
        population_1 = j['population']
        county_1 = j['nameofcounty']
        if county_1 == county: #To check if they are the same thing
            total_population = population_1 population #adds them
            print(county, total_population) #Print

This method above is however not so efficient. I personally suggest trying:

import json    
with open('test.json') as file: 
    package_json = json.load(file)
IN = package_json['States']['Illinois']['county']
IL = package_json['States']['Indiana']['county']

for i,j in zip(IN,IL): #zip() basically makes it combined
    print(i['nameofcounty'],i['population'] j['population'])

Both have the same output, but the second one is more efficient in your case. For more info about zip() you can check the docs

  • Related