Dictionary Comprehensions in Python | by Luay Matalka | Nov, 2020


How to use dictionary comprehensions to create dictionaries in python

Luay Matalka
Photo by Tianyi Ma on Unsplash

Creating a Dictionary

Let’s say that we want to create a dictionary in python from another iterable object or sequence, such as a list. For example, we have a list of numbers, and we want to create a dictionary that counts how many times each element occurs in that list. Thus, we can have the keys of the dictionary being the different elements (or numbers) in the list, and their corresponding values equal to the number of times that specific element (or number) shows up in the list.

We can use a for loop to create this dictionary as follows:

Notice how we had to first create an empty dictionary, count_dict. Then as we loop through num_list using a for loop, we are creating key:value pairs in count_dict. The key will equal the current number we are on while iterating through num_list, and its corresponding value is equal to the count of that number in num_list.

count() is a list method that returns the number of times the value we pass in occurs in our list.


Source link

Write a comment