DEV Community

Afiz
Afiz

Posted on

How to create dictionary with two lists in Python

In this post, we will discuss 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']
Enter fullscreen mode Exit fullscreen mode

expected output:

{'name': 'Afiz', 'age': 30, 'contact': '9090909090'}
Enter fullscreen mode Exit fullscreen mode

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)

Enter fullscreen mode Exit fullscreen mode

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)))
Enter fullscreen mode Exit fullscreen mode

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: https://youtu.be/PFsP2U4_GH0

Top comments (1)

Collapse
 
rupen4678 profile image
rupen4678

just

lists

first = [ ]
second = [ ]

depends how you want it

dic = {
'firstList': first,
'secondList': second,
}