0

I have state, county and aqi data. When I put in function the state name, it gives me the county and county's aqi like this:

pa_dict = county_counter('Pennsylvania')

{'Erie': 7, 'Philadelphia': 12, 'Dauphin': 6, 'Lancaster': 1, 'Berks': 3, 'Lackawanna': 7, 'Washington': 7, 'Allegheny': 21, 'Luzerne': 1, 'Schuylkill': 3, 'Beaver': 4, 'Cambria': 6, 'Monroe': 1, 'Westmoreland': 5, 'Bucks': 5, 'Lawrence': 3, 'Lehigh': 1, 'York': 1, 'Montgomery': 1, 'Adams': 2, 'Northampton': 1, 'Blair': 2}

Then I want to find Washington's aqi data which is 7, but I get a typeerror:

pa_dict = county_counter('Pennsylvania')

print(pa_dict['Washington'])

TypeError Traceback (most recent call last) in 1 pa_dict = county_counter('Pennsylvania') 2 ----> 3 print(pa_dict['Washington'])

TypeError: 'NoneType' object is not subscriptable

How can I fix the error?

edit: here is my first code:

def county_counter(state):
    county_dict={}
    for county, aqi in aqi_dict[state]:
        if county in county_dict:
            county_dict[county]+=1
        else:
            county_dict[county]=1
    print(county_dict)
county_counter('Pennsylvania')
  • 1
    probably your `county_counter` function is exausting an original source, thus when you execute the command again you have a `None` instead of the first dict you mentioned – crissal Jul 09 '23 at 08:59
  • 1
    Does this answer your question? [What is the purpose of the return statement? How is it different from printing?](https://stackoverflow.com/questions/7129285/what-is-the-purpose-of-the-return-statement-how-is-it-different-from-printing) – slothrop Jul 09 '23 at 09:14
  • yes! thank you so much @slothrop – gizem kurşova Jul 09 '23 at 09:23

1 Answers1

0
def county_counter(state_name):
    counties = {} # create an empty dictionary to store the county data
    for i, row in aqi_df.iterrows():
        if row['State'] == state_name:
            county_name = row['County']
            if county_name in counties:
                counties[county_name] += 1
            else:
                counties[county_name] = 1
    return counties
  • I should have used return but I used print. So, I got the error. Thanks everyone – gizem kurşova Jul 09 '23 at 09:12
  • `aqi_df.iterrows()`, and the references to row objects, don't look right here. OP is working with a dictionary, not a dataframe. – slothrop Jul 09 '23 at 09:13
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 10 '23 at 11:01