Python: compare one list's index to another, append second list value to first list
Question: I have a .csv file as follows (snippet).

    
    
    Country,Year,GDP ($US),Population
    Angola,2002,11431738368,10760510
    Angola,2005,32810672128,11706954
    Antigua and Barbuda,2002,714677760,67448
    Antigua and Barbuda,2005,875751360,68722
    Argentina,2002,1.02E+11,38331121
    Argentina,2005,1.83E+11,39537943
    Armenia,2002,2376335104,3013818
    Armenia,2005,4902779392,2982904
    ...
    

I need to find the five lowest GDP/Pop countries for 2002, then find their
corresponding GDP/Pop values in 2005, then compute the difference and the
percent difference. There are blanks for either GDP or Population values for
some records, which I omit.

So far I used

    
    
    import csv
    import operator
    
    data = open('file.csv')
    read_data = csv.reader(data)
    
    thisthing = []
    for line in read_data:
    #find 2002 GDP/Pop, omit blanks, append to list
        if line[7] == '2002' and line[8] != ' ' and line[9] != ' ':
            thisthing.append([line[0], (float(line[8])/(int(line[9])))])
    
    thisthing.sort(key=operator.itemgetter(1))
    

This produces a list which print line by line as follows (Country, GDP/Pop):

    
    
    ['Burma (Myanmar)', 69.07171351277908]
    ['Burundi', 89.45864552423431]
    ['Congo (Dem. Rep.)', 99.23033109735835]
    ['Ethiopia', 109.33326343550823]
    ['Eritrea', 142.8576737907048]
    ['Guinea-Bissau', 151.110429668747]
    ['Afghanistan', 159.7524117568956]
    ['Malawi', 159.7614709537829]
    ['Sierra Leone', 174.6506490278577]
    

I want to now iterate back through 'read_data', using the country name in
'thisthing' as a conditional along with my blank prevention conditional

    
    
    and line[8] != ' ' and line[9] != ' ':
    

to select and append the 2005 GDP/Pop to 'thisthing'

I have no idea where to begin doing that, and I have been stuck here for about
a week now...any help would be most appreciated.


Answer: try this!!

    
    
    import csv 
    import operator
    
    data = open('file.csv') read_data = csv.reader(data)
    
    data_2002 = {}
    data_2005 = {}
    
    thisthing = [["country", "2002%", "2005%"]] 
    
    for line in read_data:
        try: 
            gdp = float(line[8])/(int(line[9]))
            if line[7] == '2002' and line[8] != ' ' and line[9] != ' ':
                data_2002[line[0]] = gdp
    
            elif line[7] == '2005' and line[8] != ' ' and line[9] != ' ':
                data_2002[line[0]] = gdp
        except KeyError:
            print line[0]
            continue
    
    for country in data_2002:
        thisthing.append([country, data_2002[country], data_2005[country]])
    
    print thisthing
    

