Python Program to Convert Two Lists Into a Dictionary – 2024

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

Abhishek Sharma
Abhishek Sharma

Started my Data Science journey in my 2nd year of college and since then continuously into it because of the magical powers of ML and continuously doing projects in almost every domain of AI like ML, DL, CV, NLP.

Articles: 517

Leave a Reply

Your email address will not be published. Required fields are marked *