Create dictionary from two lists

ยท

1 min read

In this post, we will learn how to create a new dictionary out of two lists. First let's see the input and expected output and then the actual source code of the problem.

input:

keys = ['name', 'age', 'contact']
values = ['Afiz', 30, '9090909090']

expected output:

{'name': 'Afiz', 'age': 30, 'contact': '9090909090'}

There are multiple ways to solve this problem.

Method 1: First let's see the simple way using for loop in Python.

my_dictionary = {}

for i in range(len(keys)):
    my_dictionary[keys[i]] = values[i]

print(my_dictionary)

This solution is okay but not great. Let's check out another method which more pythonic way of doing it.

print(dict(zip(keys, values)))

Surprised !! ๐Ÿ˜ฎ ๐Ÿ˜ฏ ๐Ÿ˜ฒ yes it is one line. Tell me which method you like in the comment section. And finally if you want the explanation of these solutions please checkout my YouTube Channel: youtu.be/PFsP2U4_GH0