Python developers often use lists and dictionaries to store data. They are both very powerful data types which offer many functionalities. Sometimes, you may need to create dictionary from lists in Python. There are several ways to do this. In this article, we will learn how to build a dictionary using two lists – one for keys and another for values.
Why Create Dictionary from Lists
Dictionary is a very useful data structure that allows you to store data as key-value pairs. It can be easily converted into JSON and vice versa. But sometimes the data that you receive or import may be present as lists. In such cases, you will need to create dictionary from lists.
How to Create Dictionary from Lists in Python
Let us say you have the following two lists.
keys = ['name', 'age', 'fruit']
values = ['John', 22, 'apple']
Let us say you want to convert the above lists into the following dictionary.
{'name': 'John', 'age': 22, 'fruit': 'apple'}
Let us look at the different ways to transform data this way.
1. Using Dict Constructor with Zip
In this solution, we use a combination of dict constructor and zip function together. Zip function accepts 2 iterable objects like lists, and returns an iterator of tuples where the first passed iterator is the 1st items of both lists paired together, the second passed iterator is the 2nd items of both lists paired together, and so on. If both lists have unequal number of items, then the result will have number of iterables equal to the smaller list.
Here is the syntax to convert the 2 lists into a dictionary.
new_dict = dict(zip(keys, values))
print(new_dict) # output is
In the above code, we enclose the result of zip() function into dict constructor. The dict constructor returns an empty dictionary or converts other data types to dictionary. So this code will return a dict result.
This approach is very fast and scalable. It does not create any intermediate data structures, and works mainly using iterators.
Please note, you need to use the dict constructor instead of wrapping the result of zip() function in curly braces {…}. Otherwise, you will get a zip object instead of dictionary.
new_dict = {zip(keys, values)}
print(new_dict) # output is {<zip object at 0x7bfe90a96040>}
2. Using Dictionary Comprehension
Dictionary comprehension is similar to list comprehension. It allows you to create dictionaries from lists using a single line expression. Here is the code to create our dictionary.
new_dict = {k: v for k, v in zip(keys, values)}
In the above code, zip function returns a series of iterables for tuples. Here each tuple consists of a pair of items from both the lists – pair of 1st items, 2nd items, and so on.
The dict comprehension will loop through the result. In each iteration, it will pick a tuple from the result of zip function and assign one item as k and the other item as v. Each k-v pair is assigned as key-value pair to the new_dict dictionary.
This solution is very easy to understand and optimized for high performance. Unlike the previous solution, you can always customize the dict comprehension, to include/exclude certain items.
3. Using itertools
If you are using older Python such as Python <=2.6 then the zip function in those versions creates a list of tuples in result. This can take up a lot of space if your lists are big. On the other hand, the zip function in Python 3 returns iterators to tuples and do not take up much space. So if you are using older Python versions, then you can use izip function available in itertools, which works the same way as zip function in Python 3.
Here is the code to convert list to dictionary using izip.
from itertools import izip
new_dict = dict(izip(keys, values))
print(new_dict) # output is {'name': 'John', 'age': 22, 'fruit': 'apple'}
This method works when both the lists have the same length. If one list is longer than the other then the length of dictionary will be same as that of the shorter list.
keys = ['name', 'age', 'fruit', 'marks']
values = ['John', 22, 'apple']
new_dict=dict(zip(keys,values))
OR
new_dict=dict(izip(keys,values))
print(new_dict) # output is {'name': 'John', 'age': 22, 'fruit': 'apple'}
If you want the dict to be as long as the longer list, then you need to use zip_longest function instead of using zip or izip. In this case, all those items in longer list, that do not have equivalent in smaller list, will be filled with None values. Here is an example where we have more keys than values. In such cases, all the keys without corresponding values will be filled with None.
from itertools import zip_longest
keys = ['name', 'age', 'fruit', 'marks', 'height']
values = ['John', 22, 'apple']
new_dict=dict(zip_longest(keys,values))
print(new_dict) # output is {'name': 'John', 'age': 22, 'fruit': 'apple', 'marks': None, 'height':None}
On the other hand, if there are more values than keys, then one key with value None will be assigned the last extra value.
from itertools import zip_longest
keys = ['name', 'age', 'fruit']
values = ['John', 22, 'apple',23, 24, 5]
new_dict=dict(zip_longest(keys,values))
print(new_dict) # output is {'name': 'John', 'age': 22, 'fruit': 'apple', None: 5}
4. Using for loop
This is the most basic but one of the most customizable solution. We simply loop through a list and in each iteration assign key-value pairs.
keys = ['name', 'age', 'fruit']
values = ['John', 22, 'apple']
new_dict={}
for k, v in zip(keys,values):
new_dict[k]=v
print(new_dict) # output is {'name': 'John', 'age': 22, 'fruit': 'apple'}
In the above code, we define an empty dictionary new_dict to store key-value pairs. We call zip() function on keys and values lists so that we get an iterator of 2-item tuples where each pair is from one list. In each iteration, we use this key and value to create a dictionary key-value pair.
This method is slower than other methods but it is easy to understand for beginners and very easy to customize as per your requirement. For example, you can choose to ignore age-22 key-value pair from dictionary as shown.
for k, v in zip(keys,values):
if k!='age' and v!=22:
new_dict[k]=v
print(new_dict) # output is {'name': 'John', 'fruit': 'apple'}
Conclusion
In this article, we have learnt how to create dictionary from lists in Python. If you want to do the conversion directly without any exclusions or modifications to the list items, then you can use a combination of dict constructor and zip function. If you want to do some customization during dict creation then you can use dict comprehension or for loop.
Also read:
How to Remove Duplicates from List in Python
How to Insert New Column to Pandas Dataframe
How to Change Order of Dataframe Columns

Sreeram Sreenivasan is the Founder of Ubiq. He has helped many Fortune 500 companies in the areas of BI & software development.