Hey guys, in this blog we will see a Python Program to Convert Two Lists Into a Dictionary.
Example 1: Using zip and dict methods
index = [1, 2, 3] domains = ['ml', 'dl', 'ai'] dictionary = dict(zip(index, domains)) print(dictionary)
Output
{1: 'ml', 2: 'dl', 3: 'ai'}
- zip takes 2 lists and merges them element-wise.
- zip(index,domain) will make a list like [(1,’ml’),(2,’dl’),(3,’ai’)].
- And then dict() method will create a dictionary from it.
Example 2: Using list comprehension
index = [1, 2, 3] domains = ['ml', 'dl', 'ai'] dictionary = {k: v for k, v in zip(index, domains)} print(dictionary)
Output
{1: 'ml', 2: 'dl', 3: 'ai'}
- This is also similar to the first one.
- But here we are not using dict(), instead, we are traversing in the zipped list and explicitly assigning key:value pairs.
Check out our other python programming examples…