This tutorial will discuss about unique ways to create a dictionary from two lists in Python.
Table Of Contents
Using zip() method
Us ethe zip() method in Python, to zip the two lists together into a zipped object. It will return a list of tuples. Each tuple will have 2 items, one from first list, and second from another list. Then pass this list of tuples into the Dictionary Constructor.
It will return a Dictionary initialised with this list of tuples, where the values in the first list listOfKeys will be used as a keys, and values from the second list listOfValues will be used as the value field in each of the pair in Dictionary.
Let’s see the complete example,
listOfKeys = ['Atharv', 'Avisha', 'Kartik', 'Justin'] listOfValues = [34, 44, 49, 39] # Zip lists to make list of tuples & pass to Dictionary Constructor # to create a Dictionary dictObj = dict(zip(listOfKeys, listOfValues)) print(dictObj)
Output
{'Atharv': 34, 'Avisha': 44, 'Kartik': 49, 'Justin': 39}
Using map() and zip() methods
In the map() method of Python, we will pass three arguments,
Frequently Asked:
- Adding Duplicate Key to a Python Dictionary
- Python : 6 Different ways to create Dictionaries
- How to Merge two or more Dictionaries in Python ?
- How to Add new keys to a Dictionary in Python?
- First argument is a Lambda function which accepts 2 arguments and return tuple created by these 2 elements.
- Second argument is the list of keys.
- Third argument is the list of values.
The map() method will apply this Lambda function on all the keys and values in the list. Basically it will iterate over all the keys and values in the list in parallel and apply the lambda function on them. Then it will store all the returned tupes into a mapped object. We can pass that map object into the dictionary constructor, to create a Dictionary from it.
Let’s see the complete example,
listOfKeys = ['Atharv', 'Avisha', 'Kartik', 'Justin'] listOfValues = [34, 44, 49, 39] # Create a Dictionary from two lists dictObj = dict(map(lambda x, y: (x, y), listOfKeys, listOfValues)) print(dictObj)
Output
{'Atharv': 34, 'Avisha': 44, 'Kartik': 49, 'Justin': 39}
Summary
We learned about two ways to create a Dictionary from two lists in Python.