
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Advertisements