
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python Program – Create dictionary from the list
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.
- Related Articles
- Python – Create dictionary from the list
- Python program to create a dictionary from a string
- How to create Python dictionary from list of keys and values?
- How to create Python dictionary from the value of another dictionary?
- Python - Create a dictionary using list with none values
- Combining values from dictionary of list in Python
- How to create Python dictionary from JSON input?
- How to create a dictionary with list comprehension in Python?
- C# program to get the List of keys from a Dictionary
- Python program to Convert Matrix to Dictionary Value List
- How to create a Python dictionary from text file?
- In Python how to create dictionary from two lists?
- Create a Series from a List, Numpy Array, and Dictionary in Pandas
- Python program to create 3D list.
- Python program to convert a list of tuples into Dictionary

Advertisements