简体   繁体   中英

How do I use a loop to iterate through a dictionary that contains lists, calculate something, and add the result to the dictionary?

I'm building a dictionary that has years (key), and a list as the value [population data, 0, 0] I was able to write a loop to add years as the dictionary keys (1950 to 1990), and import population data from a file to add as [value[0], ...]

Right now, value[1] and value[2] are empty.

How do I write a loop that iterates through my dictionary ( starting at index 1, not 0 ), calculates the population change, and puts that in value[1] ...for every item in my dictionary? ( After, I will put percent change in value[2] )

myDict = {'1950':[141902, 0, 0], '1951':[157311, 0, 0], '1952':[186006, 0, 0], .... } # etc. population data from a file object

dict_key = [1950, 1951, 1952, 1953, ... ] # 41 values total, to 1990

What I have so far:

def calculate_population_change(myDict, dict_key):

 for i in range(1, (len(dict_key))): value[i] = 7 myDict[key[i]] = [value[i], 0, 0] return myDict

I wrote value[i] = 7 as a test, to see how to put something in that spot

Thank you for taking a look.

The rest of the code is at, if you need more context: https://github.com/alexisabadger/pythonDictionaryAndList/blob/main/PopulationDataCounter.py

You can iterate through your dictionary with a foor loop and since your keys represent an ascending number stored as a String, you can convert the sting to an integer, substract one and convert that to a string again in order to get the list of the year before.

for year in myDict:
    if year != '1950':
        #Calculate the difference in population of two consecutive years.
        myDict[year][1] = myDict[year][1]-myDict[str(int(year)-1)][1]

        #Calculate the difference as a percentage
        myDict[year][2] = (1-myDict[year][1]/myDict[str(int(year)-1)][1])*100

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM