list_to_dict()

Skip Montanaro skip at pobox.com
Thu Jan 16 17:43:24 CET 2003


    maney> def list_to_dict(aList, key_indexes, value_indexes):
           ...

In 2.3 (and somewhat earlier I believe), you can call the dict() type like
so:

    >>> dict([("one", 1), ("two", 2)])
    {'two': 2, 'one': 1}

You can, of course, smash your keys and values lists together using zip():

    >>> zip(("one", "two"), (1, 2))
    [('one', 1), ('two', 2)]

If all you care about are the keys, you can use dict.fromkeys() (which is
new in 2.3):

    >>> dict.fromkeys(("one", "two"))
    {'two': None, 'one': None}
    >>> dict.fromkeys(("one", "two"), "something")
    {'two': 'something', 'one': 'something'}

Try these and see if whatver version of Python you're running supports
them.  If not, you might want to consider an upgrade.

Skip





More information about the Python-list mailing list