Main Content

Using a list of keys and a list of values to make a dictionary in Python - zip

Archive - Originally posted on "The Horse's Mouth" - 2007-04-13 01:01:33 - Graham Ellis

If you have two lists in Python and you want to use them as the keys and values of a dictionary, you might be interested on Python's zip function. It's NOT the use of zip as we know it for file compression - rather it's used to interlace (combine) elements of two lists into a list of lists.

Here's an example - two lists

names = ["Jesus","Marc","Michal","Graham"]
places = ["Spain","USA","Poland","UK"]


Combine them with zip and you get a list of 2 element lists which you can turn into a dictionary:

combo = zip(names,places)
who = dict(combo)


Here's the result:

{'Michal': 'Poland', 'Marc': 'USA', 'Graham': 'UK', 'Jesus': 'Spain'}