1

How to create dictionary with two lists in Python

 2 years ago
source link: https://dev.to/afizs/how-to-create-dictionary-with-two-lists-in-python-5cla
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Afiz

Posted on Jan 2

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK