On Sun, 09 Dec 2007 00:35:18 -0800, kettle wrote: > Hi, > I'm wondering what the best practice is for creating an extensible > dictionary-of-dictionaries in python? > > In perl I would just do something like: > > my %hash_of_hashes; > for(my $i=0;$i<10;$i++){ > for(my $j=0;$j<10;$j++){ > ${$hash_of_hashes{$i}}{$j} = int(rand(10)); > } > } > > but it seems to be more hassle to replicate this in python. I've > found a couple of references around the web but they seem cumbersome. > I'd like something compact.
Use `collections.defaultdict`: from collections import defaultdict from random import randint data = defaultdict(dict) for i in xrange(11): for j in xrange(11): data[i][j] = randint(0, 10) If the keys `i` and `j` are not "independent" you might use a "flat" dictionary with a tuple of both as keys: data = dict(((i, j), randint(0, 10)) for i in xrange(11) for j in xrange(11)) And just for completeness: The given data in the example can be stored in a list of lists of course: data = [[randint(0, 10) for dummy in xrange(11)] for dummy in xrange(11)] Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list