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']
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: https://youtu.be/PFsP2U4_GH0
Top comments (2)
just
lists
first = [ ]
second = [ ]
depends how you want it
dic = {
'firstList': first,
'secondList': second,
}
Yes, it you can create a dictionary in Python using Python dictionary datatype.