Multidimensional Dictionaries: Possible?

Skip Montanaro skip at mojam.com
Tue Jan 25 15:46:43 EST 2000


    Chris> What's the quickest way to do the equivalent of the following
    Chris> Perl in Python, again, using the above example:

    Chris> $dict{$key1}{$key2}++

    Chris> I can only think of the following, I hope there is a better way!:

    Chris> a =  dict[key1, key2]
    Chris> a = a + 1
    Chris> dict[key1, key2] = a

Well, you could skip the intermediate variable:

    dict[key1, key2] = dict[key1, key2] + 1

and/or shorten the key reference up a tad:

    k = (key1, key2)
    dict[k] = dict[k] + 1

Depends on what you're after.

Also, I didn't see the entire thread, so perhaps this was already covered,
but from what little I know of Perl, "$dict{$key1}{$key2}" references a
nested dict sort of thing.  If so, the Python construct "dict[key1, key2]"
is not the same thing.  It references a single dictionary with a key that's
the tuple (key1, key2), e.g.:

    >>> dict = {}
    >>> dict[1, 2] = 'foo'
    >>> dict.keys()
    [(1, 2)]

If what you really want are nested dicts, then you should use something like

    >>> dict = {}
    >>> dict[1] = {}
    >>> dict[1][2] = 'foo'
    >>> dict.keys()
    [1]
    >>> dict[1].keys()
    [2]

Skip Montanaro | http://www.mojam.com/
skip at mojam.com | http://www.musi-cal.com/
847-971-7098


    




More information about the Python-list mailing list