Search code examples
pythondictionaryxlrd

Creating multiple dictionary variables with loop commands?


This is my first time working with python. I'm trying to create a dictionary for each county (23 in total) with year as the key for population and income values. Strong arming the code seems to work, but I'm sure there is an easier way to do it using loops or classes...any suggestions?? Thanks!!!!!

import xlrd

wb= xlrd.open_workbook('C:\Python27\Forecast_test.xls')

popdata=wb.sheet_by_name(u'Sheet1')
incomedata=wb.sheet_by_name(u'Sheet2')

WyomingCnty =('Albany', 'Big Horn',
        'Campbell', 'Carbon', 'Converse',
        'Crook', 'Fremont', 'Goshen',
        'Hot Springs','Johnson', 'Laramie',
        'Lincoln', 'Natrona','Niobrara',
        'Park', 'Platte', 'Sheridan', 'Sublette',
        'Sweetwater', 'Teton', 'Uinta', 'Washakie', 'Weston','Wyoming')

Years = ('y0','y1','y2','y3','y4','y5','y6','y7','y8','y9','y10',
    'y11','y12', 'y13', 'y14', 'y15', 'y16', 'y17', 'y18','y19',
    'y20','y21','y22','y23','y24','y25','y26','y27','y28','y29','y30')

AlbanyPop = popdata.col_values(colx=1,start_rowx=1,end_rowx=None)
AlbanyIncome= incomedata.col_values(colx=1,start_rowx=1,end_rowx=None)
AlbanyDict1=dict(zip(Years,AlbanyPop))
AlbanyDict2=dict(zip(Years,AlbanyIncome))

BigHornPop = popdata.col_values(colx=2,start_rowx=1,end_rowx=None)
BigHornIncome= incomedata.col_values(colx=2,start_rowx=1,end_rowx=None)
BigHornDict1=dict(zip(Years,BigHornPop))
BigHornDict2=dict(zip(Years,BigHornIncome))

Solution

  • popdict = {}
    incdict = {}
    for ix, city in enumerate(WyomingCnty):
      popdict[city] = dict(zip(Years, popdata.col_values(colx=ix + 1,start_rowx=1,end_rowx=None)
      incdict[city] = dict(zip(Years, incomedata.col_values(colx=ix + 1,start_rowx=1,end_rowx=None)