Dictionary Comprehension

İlkay Çil
3 min readOct 8, 2022

--

Dictionary is a data structure that holds items with key-value pairs. In Dictionary, we can access values ​​with a certain key value instead of index.

Just like real dictionaries!

The items in a dictionary can have any data type.

What is dictionary comprehension?

Dictionary comprehension is a method for converting one dictionary to another. During this conversion, items from the original dictionary can be conditionally included in the new dictionary and each item can be converted as needed.

! Dictionary comprehensions are important as life-saving.

You ask why?

  1. Their values ​​can remain the same when making changes to their keys.
  2. Keys can remain the same when making changes to values.
  3. Changes can be made on Key-Value pairs at the same time.

This template is the general use of dictionary comprehensions:

dict_= {key:value for (key,value) in dictonary.items()}

Let’s make an example 🥳

gym_customers={"Burcu":[22,150],
"Zeynep":[20,250],
"Esra":[25,250],
"Berk":[18,150],
"Can":[30,300] }

We have a dictionary of customers who go to the same gym. Key values ​​include the names of the customers. In the Value section, there are the age of the customers and the monthly fees they pay to the gym. (One-year memberships pay 150 currencies, 3-month memberships pay 250 currencies, and 1-month memberships pay 300 currencies.)

First, let’s say we wanted to print the names of our customers in upper

Input:

{k.upper():v for k,v in gym_customers.items() }

Output:

{'BURCU': [22, 150],
'ZEYNEP': [20, 250],
'ESRA': [25, 250],
'BERK': [18, 150],
'CAN': [30, 300]}

Remember, if we want to store it in capital letters like this, we have to assign it to the gym_customers dictionary again ☺️

Now that we have decided to increase the prices in the gym by 20%, we are curious about the new fees our customers will pay!

Input:

dict_new_prices = {k:v[1]*1.2 for k,v in gym_customers.items() }

Output:

{'Burcu': 180.0,
'Zeynep': 300.0,
'Esra': 300.0,
'Berk': 180.0,
'Can': 360.0}

If Condition

Let’s say we decided to offer a 10% discount to our customers who are 30 or older:

Input:

{k:v[1]*0.90 for k,v in gym_customers.items() if v[0] >= 30 }
or
{k:v[1]-v[1]*0.10 for k,v in gym_customers.items() if v[0] >= 30 }

Output:

{'Can': 270.0}

If-Else Conditions

Can’s monthly membership has expired. We now only have 3-month and annual members. We want to see who has what type of membership in the dictionary:

gym_customers={"Burcu":[22,150],
"Zeynep":[20,250],
"Esra":[25,250],
"Berk":[18,150],}

Input:

{k:("3 month membership" if v[1]==250  else "annual membership") for k,v in gym_customers.items()}

Ouput:

{'Burcu': 'annual membership',
'Zeynep': '3 month membership',
'Esra': '3 month membership',
'Berk': 'annual membership'}

See you in new articles 🙋‍♀️🙋‍♀️🙋‍♀️

--

--