When it is required to create a dictionary from a list, a dictionary is created using ‘dict’ method, a simple iteration and the ‘setdefault’ method is used.
Example
Below is a demonstration of the same −
my_dict = dict() print("An empty dictionary has been created") my_value_list = ['15', '14', '13', '12', '16'] print("The list is : " ) print(my_value_list) my_value_list.sort() print("The list after sorting is :") print(my_value_list) for value in my_value_list: for element in range(int(value), int(value) + 2): my_dict.setdefault(element, []).append(value) print("The resultant dictionary is : ") print(my_dict)
Output
An empty dictionary has been created The list is : ['15', '14', '13', '12', '16'] The list after sorting is : ['12', '13', '14', '15', '16'] The resultant dictionary is : {12: ['12'], 13: ['12', '13'], 14: ['13', '14'], 15: ['14', '15'], 16: ['15', '16'], 17: ['16']}
Explanation
An empty dictionary is created.
A list is defined and is displayed on the console.
The list is sorted using a sort method and is displayed on the console.
The list is iterated over, and the default value is added to the empty dictionary, and the value is also appended to the dictionary.
This is assigned to a result.
This is displayed as output on the console.