7 Feb 2007 lkcl   » (Master)

this is _way_ cool code, and i wrote it :)

def add_d2(*args): """ cool function for making dictionaries of dictionaries ad infinitum.

1st arg: top-level dictionary of .... of .... of ... of dictionaries [... keyname for dictionary of dictionaries of dictionaries ...] [... keyname for dictionary of dictionaries ...] [... keyname for last dictionary ...] final arg: value to be stored. """

dict_list = [args[0]] key_names = list(args[1:-1]) val = args[-1]

for keyname in key_names[:-1]: dict_list.append(dict_list[-1].setdefault(keyname, {})) dict_list[-1][key_names[-1]] = val

you use it like this:

    d = {}
    add_d2(d, keyname1, keyname2, asmanykeynamesasyouwant, val)

and then you can do this:

    print d[keyname1][keyname2][asmanykeysasyouwant]

and it will return val.

i've been using a two-dimensional dictionary-of-dictionaries-of-values for quite some time in some of the code i've been working on, and when i needed a third dimension i went RRRRIGHT, that's it, i'm writing a multi-dimensional dictionary-storing-thing.

it even works for 1-dimensional dictionary things (duh, so why bother?? just do d[x] = y but yes, if you have a function which does multidimensional storage then it's useful not to have to special-case 1 dimension)

y'know... _just_ sometimes, a simple bit of code can be... really cool :)

Latest blog entries     Older blog entries

New Advogato Features

New HTML Parser: The long-awaited libxml2 based HTML parser code is live. It needs further work but already handles most markup better than the original parser.

Keep up with the latest Advogato features by reading the Advogato status blog.

If you're a C programmer with some spare time, take a look at the mod_virgule project page and help us with one of the tasks on the ToDo list!