How to use dict() method In Python

Using dict() method we can convert list comprehension to the dictionary. Here we will pass the list_comprehension like a list of tuple values such that the first value act as a key in the dictionary and the second value act as the value in the dictionary.

Syntax: dict(list_comprehension)

Example 1: Python program to create a student list comprehension and convert it into a dictionary.

Python3




# create a list comprehension with student age
data = [('sravan', 23), ('ojaswi', 15),
        ('rohith', 8), ('gnanesh', 4), ('bobby', 20)]
 
# using dict method
dict(data)


Output:

{'bobby': 20, 'gnanesh': 4, 'ojaswi': 15, 'rohith': 8, 'sravan': 23}

We can also use the following for loop inside the dict() method.

Syntax: dict([(key,value) for key,value in data])                         

Example 2:

Python3




# create a list comprehension with student age
data = [('sravan', 23), ('ojaswi', 15),
        ('rohith', 8), ('gnanesh', 4), ('bobby', 20)]
 
# using dict method inside for loop
dict([(key, value) for key, value in data])


Output:

{'bobby': 20, 'gnanesh': 4, 'ojaswi': 15, 'rohith': 8, 'sravan': 23}

Create a dictionary with list comprehension in Python

In this article, we will discuss how to create a dictionary with list comprehension in Python.

Similar Reads

Method 1: Using dict() method

Using dict() method we can convert list comprehension to the dictionary. Here we will pass the list_comprehension like a list of tuple values such that the first value act as a key in the dictionary and the second value act as the value in the dictionary....

Method 2: Using zip() with dict() method

...

Method 3: Using Iterable

...

Method 4: Add Filter

Here in this method, we will create two lists such that values in the first list will be the keys and the second list values will be the values in the dictionary....