Multidimensional Dictionaries: Possible?
Tim Peters
tim_one at email.msn.com
Mon Jan 24 19:45:45 EST 2000
[Jerry Gardner]
> Are multidimensional dictionaries possible in Python?
Certainly.
> I'm sure they're possible, but I can't figure out the syntax.
>
> Here's how I do it in Perl:
>
> %dict = (); # create empty dictionary
>
>
> $dict{$key1}{$key2} = $string; # make an entry
> $newstring = ${dict{$key1}{$key2}}; # access an entry
Python doesn't have autovivification (unless you subclass UserDict to supply
it yourself). You have to create intermediate data structures explicitly:
dict = {}
dict[key1] = {}
dict[key1][key2] = string
newstring = dict[key1][key2]
Python rarely assumes you know what you're doing <wink -- but while that
sometimes adds more typing, it often saves your butt>.
Note too that you can use dict[key1, key2, ...] to "fake" a multidimensional
dict. Sometimes that's more appropriate. The equivalent in Perl
interpolates the multiple subscripts into a string; Python's dicts are more
general (can be indexed by any immutable object, not just strings), and
Python constructs a *tuple* of keys under the covers. That's faster and
can't suffer accidental "superkey" collisions.
More information about the Python-list
mailing list