list_to_dict()

maney at pobox.com maney at pobox.com
Thu Jan 16 16:14:59 CET 2003


Motivation:  I have configuration/errata records that arrive as a list
of records; each record is itelf a list (hereafter a sublist).  For the
intended use I want to map each of these lists into a dictionary; the
dictionary's key is one or more of the sublist elements (fields), as
are the dictionary's values; multiple values are wrapped up as a tuple,
of course, but it is preferred for single objects to stand alone.  The
indexes of and number of fields that make up the keys and values varies
from dictionary to dictionary.

So I have found myself writing a lot of similar little loops that all
look more or less alike:

    aDict = {}
    for r in aList:
        aDict[(r[1],r[2])] = (r[0],r[2],r[3],r[5])

Since I hate repeating myself, I was led, after generalizing a bit, to
the following provisional solution:

def list_to_dict(aList, key_indexes, value_indexes):

    if len(key_indexes) > 1:
        def k(): return tuple([a[i] for i in key_indexes])
    else:
        def k(): return a[key_indexes[0]]
    if len(value_indexes) > 1:
        def v(): return tuple([a[i] for i in value_indexes])
    else:
        def v(): return a[value_indexes[0]]

    res = {}
    for a in aList:
        res[k()] = v()
    return res

Of course this relies upon nested scopes as written.  I'm not entirely
happy about this factoring, though it does avoid placing the "single
object or tuple?" decision inside the loop... even if that is probably a
premature optimization for my use, it's just too ugly the other way.

I had expected to find something like this already in the Cookbook, but
I didn't.  At least not as a stand-alone - I didn't sift through any
number of things that searching turned up that might have included
something like this as a component of a larger recipie.




More information about the Python-list mailing list