How to Create a dictionary with list comprehension in Python

In this tutorial, we are going to learn How to Create a dictionary with list comprehension in Python. We are going to do this by three methods. First, let’s understand what is a dictionary in python.

The data stored in Dictionary is in key: value pair form. It consists of an ordered collection of items or objects. In which duplicates are not allowed but we can change values. Let’s see the first method.

Also read: How to add Dictionary to Dictionary in Python?

Dictionary with list comprehension using the Iterable method

# a list comprehension with vehicle and seats
info = [('Car', 4), ('Bus', 40),
    ('Jeep', 6), ('van', 8)]


# iterable method
d1 = {key: val for (key, val) in info}
print(d1)

As you can see in the above code. Here, we are going to take data of vehicles and their seating capacity in form of tuples. This data is combined in list form in list info. So it will become a list of tuples. Next, we are using list comprehension to store this information in key: value format. For that, we are using for loop.
Finally, we are storing this dictionary in variable d1 and printing it. The output will be.

Output

{'Car': 4, 'Bus': 40, 'Jeep': 6, 'van': 8}

Dictionary with list comprehension using the dict method

This is the second method. We can create a dictionary by using dict keyword. Let’s see the example below.

# a list comprehension with vehicle and seats
info = [('Car', 4), ('Bus', 40),
    ('Jeep', 6), ('van', 8)]

# dict method
d2 = dict([(key, val) for key, val in info])
print(d2)

We have taken similar information as in the above example. In the dict method, we are simply going to convert the list comprehension to the dictionary using the dict keyword.  For this we are going to use a similar key: value pair and for loop.
Finally, we are storing this dictionary in variable d2 and printing it. The output will be.

Output

{'Car': 4, 'Bus': 40, 'Jeep': 6, 'van': 8}

Another method of doing this task is

Dictionary with list comprehension using zip method

lst1=['name','age','weight','height']
lst2=['Rohan',21,63,165]
d3 = dict(zip(lst1,lst2))
print(d3)

Here, we are taking two separate lists lst1, lst2. In the first list, there are keys and in the second list, there are values. Then we are going to combine these two lists using zip keyword and convert them into dictionary using dict keywords.
Finally, we are storing this dictionary in variable d3 and printing it. The output will be.

Output

{'name': 'Rohan', 'age': 21, 'weight': 63, 'height': 165}

 

Leave a Reply

Your email address will not be published.