Converting to lists into one dictionary

Skip Montanaro skip at mojam.com
Mon Oct 4 13:51:00 EDT 1999


    Boudewijn> I was wondering whether it is possible to convert two lists
    Boudewijn> into one dictionary with one simple function: i.e., I've got
    Boudewijn> a list of keys, and a list of values like this:

    Boudewijn> list1=['a','b','c']
    Boudewijn> list2=['aaa','bbb','ccc']

    Boudewijn> and I want do something easy and speedy to these two lists
    Boudewijn> that will give me:

    Boudewijn> dict1={'a': 'aaa', 'b': 'bbb', 'c': 'ccc'}

Sure.  Try:

    >>> list1=['a','b','c']
    >>> list2=['aaa','bbb','ccc']
    >>> dict1={}
    >>> for k, v in map(None, list1, list2):
    ...   dict1[k]=v
    ... 
    >>> print dict1
    {'b': 'bbb', 'c': 'ccc', 'a': 'aaa'}

It also does the None pad of list2 you asked about.  It will None pad list1
as well, resulting in probably not what you want (the last element of list2
being associated with the key None).

Skip Montanaro | http://www.mojam.com/
skip at mojam.com | http://www.musi-cal.com/
847-971-7098   | Python: Programming the way Guido indented...




More information about the Python-list mailing list