How to convert list to dictionary in python?
A dictionary is a set of unordered key, value pairs. In a dictionary, the keys must be unique and they are stored in an unordered manner.
To build a dictionary separate the key and value pairs by a colon(:). The keys need to be an immutable type i.e. data types for which the keys cannot be changed at runtime such as int, string, tuple, etc. Individual pairs will be separated by a comma(,) and the whole thing will be enclosed in curly braces({…..}).
A list is a data structure, or it can be considered as a container that can be used to store multiple data at once. A list will be ordered and there will be a definite count of it.
We have some method by which we can convert list into dictionary in python.
- zip()- This function is used to convert lists into dictionary.
e.g.,
a=['Python', 'C++', 'Java', 'C'] b=[1, 2, 3, 4] s=dict(zip(a, b) print(s)
- fromkeys()- This function is also used to convert list into dictionary. But every key name is same in the converted dictionary.
e.g.,
a=['Python', 'Cpython', 'Java'] s=dict.fromkeys(a, "Programming_language") print(s)
In this way we can convert list into dictionary in python.