Dictionary Comprehensions in Python

Dictionary Comprehensions in Python

How to use dictionary comprehensions to create dictionaries in python

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:

num_list = [1,1,7,3,5,3,2,9,5,1,3,2,2,2,2,2,9]

count_dict = {}
for num in num_list:
    count_dict[num] = num_list.count(num)
print(count_dict)
## {1: 3, 7: 1, 3: 3, 5: 2, 2: 6, 9: 2}

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.

data-science machine-learning python programming software-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

ML Optimization pt.1 - Gradient Descent with Python

In this article, we explore gradient descent - the grandfather of all optimization techniques and it’s variations. We implement them from scratch with Python.

Hire Machine Learning Developers in India

We supply you with world class machine learning experts / ML Developers with years of domain experience who can add more value to your business.

Data Science Projects | Data Science | Machine Learning | Python

Practice your skills in Data Science with Python, by learning and then trying all these hands-on, interactive projects, that I have posted for you.

Data Science Projects | Data Science | Machine Learning | Python

Practice your skills in Data Science with Python, by learning and then trying all these hands-on, interactive projects, that I have posted for you.

Data Science Projects | Data Science | Machine Learning | Python

Practice your skills in Data Science with Python, by learning and then trying all these hands-on, interactive projects, that I have posted for you.