Merging two lists as a dictionary

Thomas Wouters thomas at xs4all.nl
Wed Jul 21 09:35:39 EDT 1999


On Wed, Jul 21, 1999 at 02:19:46AM +0000, Chris Frost wrote:

> I have two lists and would like to merge them into a dictionary, with one
> list forming the keywords and the other the values in the dictionary. How could
> this be done? "map(None, keyword_list, value_list)" looked great, but it
> returns a list of pairs (I'd like to be able to specify values according to
> keywords...).

>>> keywords = ['s','p','a','m']           
>>> values = ['eggs', 'ham', 'toast', 'omelet']
>>> result = {}
>>> for i in range(min(len(keywords), len(values))):
...     result[keywords[i]] = values[i]
... 
>>> result
{'m': 'omelet', 's': 'eggs', 'p': 'ham', 'a': 'toast'}

the 'min()' is unecessary if you are 100% certain the lists are same length,
or if you know which list will be the shorter one. (iter over the shortest
one, in that case)

-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list