Create Dictionary Using List with None Values in Python
Suppose you are given a list but we want to convert it to dictionary. Dictionary elements hold two values are called key value pair, we will use in case of value. The elements of the list become keys and non will remain a placeholder.
With dict
The dict() constructor creates a dictionary in Python. So we will use it to create a dictionary. The fromkeys method is used to create the dictionary elements.
Example
listA = ["Mon","Tue","Wed","Thu","Fri"] print("Given list: \n", listA) res = dict.fromkeys(listA) # New List print("The list of lists:\n",res)
Output
Running the above code gives us the following result −
Given list: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] The list of lists: {'Mon': None, 'Tue': None, 'Wed': None, 'Thu': None, 'Fri': None}
With zip and dict
We can also use the dict constructor with zip method so that each element is converted into a key value pair.
Example
listA = ["Mon","Tue","Wed","Thu","Fri"] print("Given list: \n", listA) res = dict(zip(listA, [None]*len(listA))) # New List print("The list of lists:\n",res)
Output
Running the above code gives us the following result −
Given list: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] The list of lists: {'Mon': None, 'Tue': None, 'Wed': None, 'Thu': None, 'Fri': None}
With dict comprehension
Create a for loop to loop through each element of the list and assign None as key.
Example
listA = ["Mon","Tue","Wed","Thu","Fri"] print("Given list: \n", listA) res = {key: None for key in listA} # New List print("The list of lists:\n",res)
Output
Running the above code gives us the following result −
Given list: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] The list of lists: {'Mon': None, 'Tue': None, 'Wed': None, 'Thu': None, 'Fri': None}
Advertisements