[Tutor] Multi-Dimensional Dictionary that contains a 12 element list.

Kent Johnson kent37 at tds.net
Wed Dec 28 17:30:31 CET 2005


Paul Kraus wrote:
> I am trying to build a data structure that would be a dictionary of a 
> dictionary of a list.
> 
> In Perl I would build the structure like so $dictionary{key1}{key2}[0] = X
> I would iterate like so ...
> foreach my $key1 ( sort keys %dictionary ) {
> 	foreach my $key2 ( sort keys %{$dictionary{$key1}} ) {
> 		foreach my $element ( @{$dictionary{$key1}{$key2} } ) {
> 			print "$key1 => $key2 => $element\n";
> 		}
> 	}
> }
> 
> Sorry for the Perl reference but its the language I am coming from. I use data 
> structures like this all the time. I don't always iterate them like this but 
> If i can learn to build these and move through them in python then a good 
> portion of the Perl apps I am using can be ported.
> 
> Playing around I have come up with this but have no clue how to iterate over 
> it or if its the best way. It seems "clunky" but it is most likely my lack of 
> understanding.
> 
> dictionary[(key1,key2)]=[ a,b,c,d,e,f,g ... ]
> 
> This i think gives me a dictionary with two keys ( not sure how to doing 
> anything usefull with it though) and a list.

This gives you a dict whose keys are the tuple (key1, key2). Since 
tuples sort in lexicographical order you could print this out sorted by 
key1, then key2 with

for (key1, key2), value in sorted(dictionary.iteritems()):
   for element in value:
     print key1, '=>', key2, '=>', element

(Wow, Python code that is shorter than the equivalent Perl? There must 
be some mistake! ;)
> 
> Now I am not sure how I can assign one element at a time to the list.

Assuming the list already has an element 0, use
dictionary[(key1, key2)][0] = X

Python lists don't create new elements on assignment (I think Perl lists 
do this?) so for example
dictionary[(key1, key2)][10] = X

will fail if the list doesn't already have 11 elements or more. You can 
use list.append() or pre-populate the list with default values depending 
on your application.

Kent



More information about the Tutor mailing list