Convert List to Dictionary in Python

Published on:
October 10, 2022

Python lists and dictionaries are two data structures stored in Python. A list in Python is an ordered succession of items, but dictionaries are not. Things in the list can be retrieved via an index (depending on their position), but things in the dictionary can only be accessed via keys.

As tech author Dimitrije Stamenic remarks, “In other words, it can store different types of data (like integers, strings, and even other lists) in an ordered sequence.” 

Lists provide for storing values in an ordered fashion, whereas dictionaries allow storing data with specific keys that match the values they include.

MarsDevs will show you the steps to convert a Python List to a Dictionary using different methods or processes in this article.

So, let’s get started!

Python Lists and Dictionaries

Python List is an ordered collection of items of any data type, including numbers, texts, and other lists. Square brackets [] to define lists.

Here is an example of a Python List with three integers:

If you want to create an empty list, here's your syntax.

On the other hand, a Dictionary is a built-in data structure in Python that contains key-value pairs. In other computer languages, dictionaries are called associative Python arrays or hash tables. Curly braces or the built-in dict() function generate a Python dictionary.

Here's an example of how to make a dictionary:

In this case, my_dict is a dictionary with three key-value pairs. The keys are 'kiwi,' 'apple,' and 'mango,' and the associated values are 1, 2, and 3, respectively.

To create an empty dictionary, here’s your syntax.

Now that we have covered the basics, let’s move on to converting a Python list to a dictionary!

Convert List to Dictionary in Python

List and Dictionary are both widely used data types in Python. In a List, data is stored in an array, whereas in a Dictionary, the data is stored in key-value pairs.

There are different ways of converting a list to a dictionary in Python, like using the counter(), zip(), and enumerate() methods.

Now let's discuss why there is a need to convert a list to a dictionary:

  • Suppose we have a list of subjects opted for by a class, and we need to count the frequency of each subject appearing in the list. We can fulfill this use case by converting this list to a dictionary.
  • Now let’s take another use case. We have one list containing alphabets and the second list containing their ASCII values. Our use case is to map the alphabet against their ASCII values. In this case, we need to convert the lists into a dictionary.

Let's discuss examples of lists and dictionaries to understand the topics.

We will learn the different methods for converting a list into a dictionary.

(i) Using Dictionary Comprehension

Dictionary Comprehension is a powerful method for converting one dictionary to another. While performing this comprehension, i.e., transforming one dictionary to another, the data can be included or excluded, conditionally, into the new dictionary.

Let’s look at the example of dictionary comprehension.

Explanation: 

  • Line 1 - Here, we take the input for n
  • Line 2 -  Here, using dictionary comprehension, we created a dictionary having numbers as its keys and their cube as its value
  • Line 3 - In this, we printed the dictionary

Output: 

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

But our main task is to convert the list to a dictionary, so we are using dictionary comprehension.

The above example shows that the second element is the square of the first element, and so on.

(ii) Using the zip() method

This method creates a zip (where the first element passed in each iterator is paired with a second element passed in each iterator). This method uses an iterator (list, tuple, dictionary object) as the parameter. 

If the length of iterators varies, then the iterator with a small length will decide the length of the resultant object. We will iterate with min length iterate and will discard the remaining values from the larger list.

Syntax:

(iii) Using dict.fromkeys() method

The method dict.fromkeys() returns the keys mapped with their specific values. The method takes sequence(list) and value (which need to be mapped with the sequence) as the input & returns the dictionary. If no value input is given to dict.fromKeys() method, it will return a dictionary with values as ‘None.’

Syntax:

dict.fromkeys(sequence, val)

Steps involved

  • Create a sequence (list) that contains data.
  • Now pass the second parameter to the dict.fromKeys() method.
  • Now call the method, and it will return the required dictionary.

(iv) Using Tuples

It is the simplest way of converting a list to a dictionary. In this process, we will create a list of tuples, each tuple containing (key-value pair). Later, this can be converted into a dictionary using the typecast method.

Steps involved

  • Creating a list of tuples and initializing them.
  • Create an empty dictionary.
  • Converting that list to a dictionary using typecasting.

(v) Converting list having alternate keys, and values to Dictionary

This method needs to be clarified. First, we will create a list of alternate key-value pairs, then match the first key to the third value, the second key to the fourth value, and so on. This is a matching of even-even elements with odd-odd elements.

Steps involved

  • Create a list having alternate key-value pairs.
  • Now slicing the list to achieve the task.
  • Now we will use dictionary comprehension.

(vi) Converting a list of dictionaries to a Dictionary

As the name suggests, in this process, we have a list of dictionaries & we will combine all these dictionaries to form one single dictionary.

Steps involved

  • Creating a list of dictionaries.
  • Using dictionary comprehension, we will convert them to a single Dictionary.

(vii) Using enumerate() method

The enumerate() method adds a counter to the iterators and returns an enumerator object. This method can be directly used in loops for converting a list to Dictionary.

Syntax :

enumerate(iterable, start = 0)

Iterable can be any iterator object like a list, dict, etc. The start is the index value from which the counter needs to be started.

Steps involved

  • Create a list. It can be of any type.
  • Now call the enumerate() method by passing the list created in the parameter along with the index value of the counter.
  • We will get an enumerator object now and typecast it into the dictionary.
  • Then print the resultant dictionary.

(viii) Using the counter() method

Now here, we will use the counter() method present in the collection module of Python for converting a list to a dictionary.

Steps involved

  • Create a sample list.
  • Now from the collection module, import counter() method.
  • Then type cast the result into the dictionary.

(ix) Using the map and dict method

You can also use array slicing to convert a list into a dictionary in Python. 

Steps involved

  • Build an array in Python with keys and values.
  • Produce key-value pairs as tuples using the mapping technique. 
  • Typecast to make it appropriate for dictation.

(x) Converting a list to a dictionary Using a loop

This method works by creating an empty dictionary and then iterating through the list in two-step increments. 

Steps involved

  • Each iteration adds a key-value pair to the dictionary
  • The current element is the key, and the next is the value. 
  • Finally, as a consequence, the dictionary is returned.

Syntax:

Wrapping up

In this article, we presented examples of utilizing different techniques to convert a list to a dictionary in Python. You can use the dict.fromkeys() function to convert a list to a dictionary with the same values. The Python zip() method can merge two lists into a single dictionary. Dictionary comprehension allows you to generate a new dictionary based on the values of a list.

As UpGrad writes, “By nature, lists are mutable, i.e., you can change them even after their creation.

So, now that you know the various ways to convert a list to a dictionary in Python, you're ready to start converting Python lists to dictionaries like a pro!

Need help with getting started with Python projects? Reach out to MarsDevs anytime!

FAQs

1. What is a list in Python?

Lists are used to keep several elements in one variable. Lists are one of four built-in data types in Python that are used to store data collections; the other three are Tuples, Sets & Dictionary, all have various properties and applications.

2. What is the purpose of a list?

Lists describe items based on a specified category or logical sequence to exchange information, remind, and arrange items.

3. What is a Dictionary in Python?

A dictionary in Python is an array of key-value pairs. The dictionary keys must be distinct. The dictionary value might be of any type.

4. What are the types of dictionaries in Python?

Python has 4 types of dictionaries: ChainMap, OrderedDict, DefaultDict & UserDict.

5. How to convert a list to dictionary keys?

We can transform a list into a dictionary using enumerate(), with the index as the key and the list item as the value. The function enumerate() will return an enumerate object. Using the dict() constructor, we can convert to dict.


Similar Posts