Nested dictionaries trouble

rzed rzantow at gmail.com
Sat Apr 21 15:31:44 CEST 2007


IamIan <iansan at gmail.com> wrote in
news:1177025742.252000.231430 at e65g2000hsc.googlegroups.com: 

> Thank you again for the great suggestions. I have one final
> question about creating a httpMonths dictionary like {'Jan':'01'
> , 'Feb':'02' , etc} with a minimal amount of typing. My code
> follows (using Python 2.3.4):
> 
> import calendar
> 
> # Create years list, formatting as strings
> years = map(str, xrange(1990,2051))
> 
> # Create months list with three letter abbreviations
> months = list(calendar.month_abbr)
> 
> # Create monthTotals dictionary with default value of zero
> monthTotals = dict.fromkeys(months[1:],0)
> 
> # Create yearTotals dictionary with years for keys
> # and copies of the monthTotals dictionary for values
> yearTotals = dict([(year, monthTotals.copy()) for year in
> years]) 
> 
> # Create httpMonths dictionary to map month abbreviations
> # to Apache numeric month representations
> httpMonths =
> {"Jan":"01","Feb":"02","Mar":"03","Apr":"04","May":"05","Jun":"0
6
> ","Jul":"07","Aug":"08","Sep":"09","Oct":"10","Nov":"11","Dec":"
1
> 2"} 
> 
> It is this last step I'm referring to. I got close with:
> httpMonths = {}
> for month in months[1:]:
>   httpMonths[month] = str(len(httpMonths)+1)
> 
> but the month numbers are missing the leading zero for 01-09.
> Thanks! 
> 

Maybe something like: 
httpMonths = dict((k,"%02d" % (x+1)) 
    	for x,k in enumerate(months[1:]) )

-- 
rzed



More information about the Python-list mailing list