Python Data Structures

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.

Ten different ways to convert a Python list to a dictionary

  1. Converting a list of tuples to a dictionary
  2. Converting two lists of the same length to a dictionary
  3. Converting two lists of different length to a dictionary
  4. Converting a list of alternative key, value items to a dictionary
  5. Converting a list of dictionaries to a single dictionary
  6. Converting a list into a dictionary using enumerate()
  7. Converting a list into a dictionary using dictionary comprehension
  8. Converting a list to a dictionary using dict.fromkeys()
  9. Converting a nested list to a dictionary using dictionary comprehension
  10. Converting a list to a dictionary using Counter()

1. Converting a List of Tuples to a Dictionary

The dict() constructor builds dictionaries directly from sequences of key-value pairs.

Using dict() constructor


2. Converting Two Lists of the Same Length to a Dictionary

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.

zip()

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

10 Ways to Convert Lists to Dictionaries in Python
2.20 GEEK