Nested dictionaries trouble

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Apr 11 15:23:50 EDT 2007


En Wed, 11 Apr 2007 15:57:56 -0300, IamIan <iansan at gmail.com> escribió:

> I'm writing a simple FTP log parser that sums file sizes as it runs. I
> have a yearTotals dictionary with year keys and the monthTotals
> dictionary as its values. The monthTotals dictionary has month keys
> and file size values. The script works except the results are written
> for all years, rather than just one year. I'm thinking there's an
> error in the way I set my dictionaries up or reference them...

> monthTotals = dict.fromkeys(months, 0)
> # Nest monthTotals dictionary in yearTotals dictionary
> yearTotals = {}
> for year in years:
>   yearTotals.setdefault(year, monthTotals)

All your years share the *same* monthTotals object.
This is similar to this FAQ entry:  
<http://effbot.org/pyfaq/how-do-i-create-a-multidimensional-list.htm>
You have to create a new dict for each year; replace the above code with:

yearTotals = {}
for year in years:
     yearTotals[year] = dict.fromkeys(months, 0)

-- 
Gabriel Genellina



More information about the Python-list mailing list