Python lists and dictionaries are two data structures in Python used to store data. A Python list is an ordered sequence of objects, whereas dictionaries are unordered. The items in the list can be accessed by an index (based on their position) whereas items in the dictionary can be accessed by keys and not by their position.
Let’s see how to convert a Python list to a dictionary.
The dict()
constructor builds dictionaries directly from sequences of key-value pairs.
Using dict() constructor
We can convert two lists of the same length to the dictionary usingzip()
.
zip()
will return an iterator of tuples. We can convert that zip object to a dictionary usingthe dict()
constructor.
Make an iterator that aggregates elements from each of the iterables.
“
**_zip_**_(*iterables)_
_: Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator.” — Python _documentation
#python3 #programming #devops #python #data-science