使用循环命令创建多个字典变量?

时间:2011-06-21 22:27:22

标签: python dictionary xlrd

这是我第一次使用python。我正在尝试为每个县创建一本字典(总共23个),其中年份是人口和收入价值的关键。强烈武装代码似乎工作,但我敢肯定有一个更简单的方法来使用循环或类...任何建议?感谢!!!!!

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))

2 个答案:

答案 0 :(得分:3)

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)

答案 1 :(得分:1)

我会用另一本字典。如:

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

popdata=wb.sheet_by_name(u'Sheet1')  #Import population data
incomedata=wb.sheet_by_name(u'Sheet2') #Import income data

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')

county_dict = {}
for col, county in enumerate(WyomingCnty):
    county_dict[county] = {}
    county_popdata = popdata.col_values(colx=col, start_rowx=1, end_rowx=None)
    county_incdata = incomedata.col_values(colx=col, start_rowx=1, endrowx=None)
    county_dict[county]['population'] = county_popdata
    county_dict[county]['income'] = county_incdata
    county_dict[county]['pop_by_year'] = dict(zip(Years, county_popdata)) 
    county_dict[county]['inc_by_year'] = dict(zip(Years, county_incdata))