create dictionary from lists in python

How to Make Python Dictionary from Two Lists

Python dictionaries are powerful and useful data structures used by many developers. Sometimes you may need to create python dictionary using two lists, one containing all keys and the other containing all values. In this article, we will learn how to make python dictionary from two lists.

How to Make Python Dictionary from Two Lists

Let us say you have the following two python lists, the first list containing keys to be created in our JS object, and the second list contains their corresponding values.

keys = ['name', 'age', 'food']
values = ['Joe', 32, 'Fruits']

Let us say you want to use the above lists to create the following JS object.

dict = {'name' : 'Joe', 'age' : 32, 'food' : 'Fruits'}

There are several ways to do this. We will look at some of them one by one.

1. Using dict Constructor

You can use the dict() constructor with zip() function to combine the two lists to create dictionary. Here is an example to do this.

test_dict = dict(zip(keys, values))

The zip() function above pairs the first item of both lists, then the second ones and so on. It returns a zip object which is an iterator of tuples, where each tuple contains iterators where each passed iterator is paired together. It is the fastest way to create dictionary from lists.

If you are using python <=2.6 then you should use izip instead of zip since, in those python versions, zip() function returns a list of tuples, which you need to separately convert into dictionary.

from itertools import izip as zip
test_dict = dict(izip(keys, values))

2. Using Dict Comprehension

You can also use a dict comprehension to simply loop through both both lists and use zip function to pair their corresponding iterators.

test_dict = {k: v for k, v in zip(keys, values)}

In this article, we have learnt a couple of simple ways to create dictionary out of lists.

Also read:

How to Check if JavaScript Object is Properly Defined
How to Get Difference Between Two Dates in JavaScript
How to Shuffle Array in JavaScript
How to Dynamically Create Variables in Python
How to Login to PostgreSQL Without Password

Leave a Reply

Your email address will not be published.