In this article we will learn how to create a dictionary from another frequently used python collection namely list. An index or key is not part a list content. But in dictionary we need to have a key or index attached to every element which is referred as value.
Using enumerate
The enumerate function adds a counter as the key of the enumerate object. SO we apply it to a given list and using a for loop. That creates the required dictionary where the keys are generated by the enumerate function.
Example
Alist = ['Mon', 'Tue', 'Wed', 'Wed',11,11] # Given list print("Given list : " , Alist) # Converting to DIctionary NewDict = {val: key + 1 for key, val in enumerate(Alist)} # print result print("Dictionary created with index : ",NewDict)
Output
Running the above code gives us the following result −
Given list : ['Mon', 'Tue', 'Wed', 'Wed', 11, 11] Dictionary created with index : {'Mon': 1, 'Tue': 2, 'Wed': 4, 11: 6}
Please note when there are duplicate elements only them is displayed having a higher index value from among the duplicates.
Using zip and range
Another approach is to apply the range function to create the keys starting from 1 and going up to the length of the list supplied. Finally, we apply the dict function to create the dictionary.
Example
Alist = ['Mon', 'Tue', 'Wed', 'Wed',11,11] # Given list print("Given list : " , Alist) # Converting to DIctionary NewDict = dict(zip(Alist, range(1, len(Alist)+1))) # print result print("Dictionary created with index : ",NewDict)
Output
Running the above code gives us the following result −
Given list : ['Mon', 'Tue', 'Wed', 'Wed', 11, 11] Dictionary created with index : {'Mon': 1, 'Tue': 2, 'Wed': 4, 11: 6}