list_to_dict()

Martin v. Löwis martin at v.loewis.de
Thu Jan 16 11:47:22 EST 2003


maney at pobox.com writes:

> Of course this relies upon nested scopes as written.

This limitation is easy to remove, and the list comprehension a the
same time (OTOH, it relies on lists having a __getitem__):

def unwrap(list):
    return list[0]

def list_to_dict(aList, key_indexes, value_indexes):

    if len(key_indexes) > 1:
        k = tuple
    else:
        k = unwrap
    if len(value_indexes) > 1:
        v = tuple
    else:
        v = unwrap

    res = {}
    for a in aList:
        f = a.__getitem__
        res[k(map(f,key_indexes))] = v(map(f,value_indexes))
    return res

Regards,
Martin




More information about the Python-list mailing list