Python: How to build a dictionary with two lists using zip( )

If you have two lists and would like to build a dictionary where one list will be the keys and the second list will be the values, Python has a way to do this easily using the built-inzip() function.  With small enough examples, we could build our dictionary manually by typing it at the keyboard. However, with large data sets thousands of records long, this is not practical, which is why this technique is so useful.

For example, let’s say we want to build a dictionary of fruit where the keys are the letters of the alphabet and the values are the names of the fruit. Perhaps these key-value associations are already present in a table or spreadsheet somewhere, and we can access the columns as lists:

alphabet = ["a", "b", "c", "d"]
fruit = ["apple", "banana", "cherry", "date"]

Here is the syntax for this technique:

my_dictionary = dict(zip(keys_list, values_list))

Here is the code for applying it to my two example lists. Notice you must specify that you want to create a dictionary using the dict() function:

alphabet = ["a", "b", "c", "d"]
fruit = ["apple", "banana", "cherry", "date"]
fruit_dict = dict(zip(alphabet, fruit))
print fruit_dict

Which yields:

{'a': 'apple', 'c': 'cherry', 'b': 'banana', 'd': 'date'}

Note: If there is a mismatch in the number of elements in both lists (one list is longer), then zip will only match elements one for one up to the point where there are values in both lists. For example, if my fruit list had an extra fruit that didn’t match up to a letter:

fruit = ["apple", "banana", "cherry", "date", "grape" ]

The resulting dictionary would be identical to the first example. “grape” would not be in the dictionary since it has no corresponding key in the first list. The point to remember is that the two lists will be zipped together into key-value pairs index by index, so the order of the two lists matters.

For more information, see:
https://docs.python.org/2/library/functions.html#zip

Leave a Reply