From the course: Advanced Python

Unlock this course with a free trial

Join today to access over 25,500 courses taught by industry experts.

Using dictionary comprehensions

Using dictionary comprehensions - Python Tutorial

From the course: Advanced Python

Using dictionary comprehensions

- [Instructor] Now let's take a look at how to use comprehensions when working with dictionaries. In this example, I'll use a list of Celsius temperatures. So let's suppose I wanted to build a dictionary that mapped each of these Celsius temperature values to a corresponding value in the Fahrenheit scale. So to do that, I would need to build a dictionary. So let's start by declaring a new variable called tempDict, and we'll make that an empty dictionary. Now, what I need to do in this case is create both a key and a value from each temperature in the Celsius list. So remember, what we want to be able to do is look up each Fahrenheit value given a Celsius value. So that means that each Celsius value needs to be the key, and the Fahrenheit value needs to be conversion from the Celsius. So just like we did with set comprehensions, I'm going to use curly braces to create the comprehension, but the difference is that I'm going to have a key value pair. So the key will be the temperature…

Contents