From the course: Advanced Python

Unlock the full course today

Join today to access over 22,700 courses taught by industry experts or purchase this course individually.

Dictionary comprehensions

Dictionary comprehensions - Python Tutorial

From the course: Advanced Python

Start my 1-month free trial

Dictionary comprehensions

- [Instructor] Now let's take a look at how to use comprehensions when working with dictionaries. So I'll open dictcomp_start in my editor in my Comprehensions folder, and in this example, I'll again use a list of temperatures, this time just the Celsius ones. So let's suppose I wanted to build a dictionary that mapped each Celsius temperature value with its corresponding value in the Fahrenheit scale? Now, to do that, I would need to build a dictionary where Celsius temperature will be the key and the value will be the Fahrenheit temperature for that Celsius key. So let's start by defining a new variable called tempDict, and what I need to do in this case is create both a key and a value from each temperature in the Celsius list. And remember we want to be able to look up each Fahrenheit value given the Celsius value, so that means each Celsius value needs to be the key. So inside the expression here, I'll write t colon, and that's going to be t times nine fifths plus 32. So that's…

Contents