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

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Dec 29 22:13:03 CET 2005


> ok so assuming I had a dictionary with 1key that contained a list like
> so... dictionary[key1][0]
>
> How would I increment it or assign it if it didn't exist. I assumed like
> this. dict[key1][0] = dictionary.get(key1[0],0) + X

Hi Paul,

Given a dictionary d and some arbitrary key k, let's assume two
possibilities:

   1.  k is a key in d.  If so, no problem, and we'll assume that d[k] is
       associated to some twelve-element list.

   2.  k isn't yet a key in d.  This is the situation we want to work on.


We can go the uncomplicated route and just say something like this:

    if k not in d:
        d[k] = [0] * 12

in which case we change Possibility 2 to Possibility 1: the end result is
that we make sure that d[k] points to a twelve-element list of zeros.
Once we guarantee this, we can go on our merry way.

For example:

    if k not in d:
        d[k] = [0] * 12
    d[k][0] += 1

There is a one-liner way of doing this: we can use the setdefault() method
of dictionaries.

    d.setdefault(k, [0] * 12)[0] += 1

This is a bit dense.  There's no shame in not using setdefault() if you
don't want to.  *grin*  I actually prefer the longer approach unless I'm
really in a hurry.


This being said, what data are you modeling?  It almost sounds like you're
implementing some kind of 3d matrix, even a sparse one.  More information
about the data you're modelling might lead to a different representation

For example, would using a dictionary whose keys are three-tuples be
approrpriate?

######
def increment(d, x, y, z):
    """Given a dictionary whose keys are 3-tuples, increments at the
    position (x, y, z)."""
    d[(x, y, z)] = d.get((x, y, z), 0) + 1
######

Here's this code in action:

###
>>> map = {}
>>> increment(map, 3, 1, 4)
>>> map
{(3, 1, 4): 1}
>>> increment(map, 2, 7, 1)
>>> map
{(2, 7, 1): 1, (3, 1, 4): 1}
>>> increment(map, 2, 7, 1)
>>> map
{(2, 7, 1): 2, (3, 1, 4): 1}
###


Best of wishes to you!



More information about the Tutor mailing list