Introduction
Dictionaries are a really highly effective, Pythonic strategy to retailer knowledge. They permit us to affiliate a key
with a worth
, and entry them as wanted. This makes it straightforward to retailer knowledge the place, for instance, we have to affiliate a string with a quantity. For example, if we have to retailer knowledge associated to names and related telephone numbers, then the dictionary is the very best knowledge construction to take action.
On this article, we’ll present what a dictionary is and focus on tips on how to use the dictionary comprehension methodology to create dictionaries in a Pythonic and stylish approach. Specifically, creating dictionaries with comprehension is helpful in conditions when we have now to retrieve knowledge from different knowledge constructions to retailer them in a dictionary.
What are dictionaries?
A dictionary is a Pythonic strategy to retailer knowledge that’s coupled as keys and values. Right here is an instance of how we are able to create one:
my_dictionary = {'key_1':'value_1', 'key_2':'value_2'}
One of many highly effective points of dictionaries is the truth that we have now no explicit limitations on the kind of values we are able to retailer in them.
For instance, we are able to retailer strings in addition to integers or floats, and even lists or tuples. However we are able to additionally create nested dictionaries, which means: retailer dictionaries within a dictionary.
Let’s examine some examples.
Suppose we wish to affiliate the names and the surnames of some folks. We are able to use a dictionary to retailer string values,
like so:
names = {'Doe': 'John', 'Bush': 'Simon', 'Johnson': 'Elizabeth'}
Then, if we wish to see the consequence, we are able to simply print it:
print(names)
and we get:
{'Doe': 'John', 'Bush': 'Simon', 'Johnson': 'Elizabeth'}
As a substitute, suppose we wish to retailer the names of some folks and their ages. We are able to retailer the age as int
values, like so:
ages = {'James': 15, 'Susan': 27, 'Tricia': 32}
And, once more, to see the outcomes:
print(ages)
Now, suppose we have to write down a purchasing listing. We are able to retailer the gadgets to purchase both as an inventory or tuple within the values of our dictionary. For instance, let’s use a listing
:
shopping_list = {'fruit': ['apple', 'banana', 'orange'], 'greens': ['broccoli', 'salad']}
print(shopping_list)
And we get:
{'fruit': ['apple', 'banana', 'orange'], 'greens': ['broccoli', 'salad']}
Lastly, suppose we wish to retailer some knowledge associated to a classroom. Specifically, suppose we wish to know the names, ages, and grades of some college students in a classroom. We are able to retailer this knowledge as a nested dictionary like so:
classroom = {
'student_1': {
'identify': 'Alice',
'age': 15,
'grades': [90, 85, 92]
},
'student_2': {
'identify': 'Bob',
'age': 16,
'grades': [80, 75, 88]
},
'student_3': {
'identify': 'Charlie',
'age': 14,
'grades': [95, 92, 98]
}
}
print(classroom)
and we get:
{'student_1': {'identify': 'Alice', 'age': 15, 'grades': [90, 85, 92]}, 'student_2': {'identify': 'Bob', 'age': 16, 'grades': [80, 75, 88]}, 'student_3': {'identify': 'Charlie', 'age': 14, 'grades': [95, 92, 98]}}
Now, whereas we may have to put in writing dictionaries “by hand” as we did right here, the fact is that in most programming functions, we have to create dictionaries by retrieving knowledge from totally different sources, and that is the place dictionary comprehension is useful.
What’s dictionary comprehension?
Dictionary comprehension is a helpful function in Python that enables us to create dictionaries concisely and effectively. It is a highly effective instrument that may save us effort and time, particularly when working with massive quantities of information.
It is just like listing comprehension however, as a substitute of making an inventory, it creates a dictionary. The syntax is as follows:
{key: worth for (key, worth) in iterable}
Within the above syntax, key
and worth
are the keys and values that we wish to embody within the dictionary, respectively. iterable
, however, is any iterable object, akin to a listing
, or a tuple
that accommodates the values that we wish to use as keys and values within the dictionary.
So, let’s discover the iterables we are able to use with some sensible examples.
Instance Use-Instances
Let’s look at some sensible examples to show how dictionary comprehension works in several utilization eventualities.
Reworking Dictionary Values
The primary instance we wish to showcase is tips on how to use dictionary comprehension to rework the values of a dictionary. For example, contemplate we have now the next dictionary:
Take a look at our hands-on, sensible information to studying Git, with best-practices, industry-accepted requirements, and included cheat sheet. Cease Googling Git instructions and truly study it!
original_dict = {'a': '1', 'b': '2', 'c': '3'}
On this instance, each the keys and the values are str
. Now, suppose we wish to convert the kind of the numbers to int
. We are able to use dictionary comprehension like so:
transformed_dict = {key: int(worth) for key, worth in original_dict.gadgets()}
print(transformed_dict)
So, the output of our remodeled dictionary is:
{'a': 1, 'b': 2, 'c': 3}
Filtering with if, if-else Statements, and for Loops
Suppose we have now a dictionary reporting the costs of assorted fruits, and we wish to filter the fruits with costs decrease than a sure threshold. Here is how we are able to use dictionary comprehension to perform this:
merchandise = {'apple': 1.0, 'banana': 0.5, 'orange': 1.5, 'pear': 0.75}
max_price = 0.75
cheap_products = {fruit: worth for fruit, worth in merchandise.gadgets() if worth <= max_price}
print(cheap_products)
And we have now:
{'banana': 0.5, 'pear': 0.75}
So, we have simply excluded the apple and orange as they value greater than our threshold.
Now, let’s examine one other instance the place we filter our knowledge, however on this case, we wish to use the else
assertion. For instance, contemplate we have now a dictionary reporting some fruits and their costs. We wish to create a brand new dictionary the place costs increased than 10 are discounted by 10%. Here is how we are able to achieve this:
merchandise = {'apple': 1.0, 'banana': 5.0, 'orange': 15.0, 'pear': 10.0}
discounted_products = {fruit: worth * 0.9 if worth > 10 else worth for fruit, worth in merchandise.gadgets()}
print(discounted_products)
And we get:
{'apple': 1.0, 'banana': 5.0, 'orange': 13.5, 'pear': 10.0}
So, we have now utilized a ten% low cost to the worth of the orange (the one one with a worth increased than 10).
However we are able to do extra. Suppose, for instance, that we have saved some fruits with their costs once more. We wish to extract the identify of a specific fruit and its worth. For example, think about I really like apples; so I wish to understand how a lot they value. That is what we might do:
merchandise = {'apple': 1.0, 'banana': 0.5, 'orange': 1.5, 'pear': 0.75}
my_fruit = 'apple'
my_product = {fruit: worth for fruit, worth in merchandise.gadgets() if fruit == my_fruit}
Now we are able to iterate over the brand new dictionary:
for fruit, worth in my_product.gadgets():
print(f"My favourite fruit is {fruit} and it prices {worth}")
And we get:
My favourite fruit is apple and it prices 1.0
Creating Lookup Tables
A lookup desk is an array that maps enter with output values. So, it in some way approximates a mathematical perform.
Suppose we have now two dictionaries: one mapping names to emails and the opposite mapping names to cell phone numbers. We wish to create a lookup desk that maps the names to the telephone numbers. We are able to do it like so:
names_to_emails = {'Alice': '[email protected]', 'Bob': '[email protected]', 'Charlie': '[email protected]'}
emails_to_phones = {'[email protected]': '555-1234', '[email protected]': '555-5678', '[email protected]': '555-9012'}
names_to_phones = {identify: emails_to_phones[email] for identify, e mail in names_to_emails.gadgets()}
print(names_to_phones)
And we get:
{'Alice': '555-1234', 'Bob': '555-5678', 'Charlie': '555-9012'}
Creating Dictionaries from Pandas DataFrames
We are able to use dictionary comprehension to create dictionaries by retrieving knowledge from Pandas knowledge frames. For instance, contemplate we have now an information body containing columns with names, ages, nations, and salaries of some folks. We are able to create a dictionary with names and ages like so:
import pandas as pd
df = pd.DataFrame({
'Title': ['John', 'Jane', 'Bob', 'Alice'],
'Age': [25, 30, 42, 35],
'Nation': ['USA', 'Canada', 'Australia', 'UK'],
'Wage': [50000, 60000, 70000, 80000]
})
name_age_dict = {identify: age for identify, age in zip(df['Name'], df['Age'])}
print(name_age_dict)
And we get:
{'John': 25, 'Jane': 30, 'Bob': 42, 'Alice': 35}
Creating Dictionaries from Lists and Tuples
We are able to use dictionary comprehension to create dictionaries by retrieving knowledge from lists and tuples. For instance, if we wish to retrieve some knowledge from two lists, we are able to write the next code:
names = ['John', 'Jane', 'Bob', 'Alice']
ages = [25, 30, 42, 35]
name_age_dict = {identify: age for identify, age in zip(names, ages)}
print(name_age_dict)
And we get:
{'John': 25, 'Jane': 30, 'Bob': 42, 'Alice': 35}
Observe: The code can be the identical in case we would use tuples reasonably than lists.
Conclusions
On this article, we have seen how dictionary comprehension can assist us in a wide range of sensible conditions, making it straightforward to create new dictionaries by retrieving knowledge from totally different sources. The brevity of comprehension makes creating dictionaries a easy and quick course of.