Syntax error How to create Python dictionary from list of keys and values?

How to create Python dictionary from list of keys and values?



In Python, the dictionary is one of the built-in data types that stores the data in the form of key-value pairs. The pair of key-value is separated by a comma and enclosed within curly braces {}. The key and value within each pair are separated by a colon (:). Each key in a dictionary is unique and maps to a value. It is an unordered, mutable data.

Creating dictionary from lists

In Python, we can create a dictionary by using two separate lists. One list is considered as the keys, and the second one is considered as values. We use built-in function called zip() to pair the lists together according to their index positions. And the dict() function is used to convert zipped items into a dictionary.

my_list1={1,2,3,4,5} #list1 used for keys
my_list2={'one','two','three','four','five'} #list2 used for values
my_dict=dict(zip(my_list1,my_list2)) 
print("dictionary-",my_dict)

Following is the output of the above code -

dictionary- {1: 'two', 2: 'three', 3: 'five', 4: 'four', 5: 'one'}

Creating a dictionary from a single list

We can also create a dictionary from a single list. The index values are considered as keys, and the elements of the list are considered as the values of the dictionary.

my_list=['a','b','c','d']
dic={}
for i in range(len(my_list)):
    dic[i]=my_list[i]

print(dic)

Following is the output of the above code -

{0: 'a', 1: 'b', 2: 'c', 3: 'd'}

Using enumerate() to Create a Dictionary

In Python, we have a built-in function called enumerate(), which returns an enumerate object when a list is passed as an argument. This object generates pairs of index and corresponding list elements. To create a dictionary from these pairs, we can pass the enumerate object to the dict() constructor.

my_list = ['One', 'Two', 'Three']
my_dict = dict(enumerate(my_list))
print(my_dict)

Following is the output of the above code -

{0: 'One', 1: 'Two', 2: 'Three'}
Updated on: 2025-04-17T16:41:25+05:30

24K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements