Python – Create dictionary from the list


When it is required to create dictionary from a list, the ‘fromkeys’ method in the ‘dict’ method is used.

Example

Below is a demonstration of the same −

my_list = ['Hi', 'Will', 'how', 'Python', 'cool']
print("The list is ")
print(my_list)

my_dict = dict.fromkeys(my_list, "my_value")
print(my_dict)

Output

The list is
['Hi', 'Will', 'how', 'Python', 'cool']
{'Hi': 'my_value', 'Will': 'my_value', 'how': 'my_value', 'Python': 'my_value', 'cool': 'my_value'}

Explanation

  • A list of strings is defined and is displayed on the console.

  • The ‘fromkeys’ method present in ‘dict’ is used to convert the elements of the list to dictionary keys.

  • The value for every key is specified here itself.

  • This is assigned to a variable.

  • It is displayed as output on the console.

Updated on: 08-Sep-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements