Dictionaries (or dict in Python) are a way of storing elements just like you would in a Python list. But, rather than accessing elements using its index, you assign a fixed key to it and access the element using the key. What you now deal with is a "key-value" pair, which is sometimes a more appropriate data structure for many problems instead of a simple list. You will often have to deal with dictionaries when doing data science, which makes dictionary comprehension a skill that you will want to master.
In this tutorial:
- First, you'll see what a Python dictionary really is and how you can use it effectively.
- Next, you'll learn about Python dictionary comprehensions: you will see what it is, why it is important, and how it can serve as an alternative to for loops and lambda functions.
- You will learn how to add conditionals into dictionary comprehensions: you will work with if conditions, multiple if conditions, and also if-else statements.
- Lastly, you will see what nested dictionary comprehension is, how you can use it, and how you can potentially rewrite it with for loops.
To easily run all the example code in this tutorial yourself, you can create a DataLab workbook for free that has Python pre-installed and contains all code samples. For more practice on dictionary comprehension, check out our Python Toolbox interactive course.
Learn Python From Scratch
Master Python for data science and gain in-demand skills.
What is a Python Dictionary?
A dictionary in Python is a collection of items accessed by a specific key rather than by an index. What does this mean?
Imagine a dictionary in the real world. When you need to look up the meaning of a word, you try to find the meaning using the word itself and not the possible index of the word. Python dictionaries work with the same concept: The word whose meaning you are looking for is the key, and the meaning of the word is the value. You do not need to know the index of the word in a dictionary to find its meaning.
Initializing a dictionary in Python
You can initialize a dictionary in Python this way:
a = {'apple': 'fruit', 'beetroot': 'vegetable', 'cake': 'dessert'} a['doughnut'] = 'snack' print(a['apple'])
fruit
print(a[0])
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-9-00d4a978143a> in <module>() ----> 1 print(a[0]) KeyError: 0
First, we create a dictionary named a that has three key-value pairs: 'apple': 'fruit', 'beetroot': 'vegetable', and 'cake': 'dessert'. The keys are strings that represent the names of items, and the values are strings that represent the type or category of the item.
Next, we add a new key-value pair to the dictionary a using the syntax a ['doughnut'] = 'snack'. This adds the key 'doughnut' to the dictionary with the corresponding value 'snack'.
The third line of the code prints the value associated with the key 'apple' in the dictionary a. Since 'apple' is a key in the dictionary, the code prints the value 'fruit'.
The fourth line of the code tries to print the value associated with the key 0 in the dictionary a, which is not a valid key in the dictionary. This results in a KeyError, which is raised when trying to access a key that does not exist in a dictionary.
Python dictionary data types
The items in a dictionary can have any data type. Check out some more examples of a dictionary below to get a hang of it:
Create a dictionary a with four key-value pairs:
a = {'one': 1, 'two': 'to', 'three': 3.0, 'four': [4,4.0]} print(a)
Update the value associated with the key 'one' in the dictionary a to 1.0.
# Update a dictionary a['one'] = 1.0 print(a)
{'four': [4, 4.0], 'two': 'to', 'three': 3.0, 'one': 1.0}
Delete the key-value pair associated with the key 'one' from the dictionary a.
# Delete a single element del a['one'] print(a)
{'four': [4, 4.0], 'two': 'to', 'three': 3.0}
Remove all key-value pairs from the dictionary a using the clear() method.
# Delete all elements in the dictionary a.clear() print(a)
{}
Delete the dictionary a using the del keyword.
# Delete the dictionary del a print(a)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-12-701c9d6596da> in <module>() 1 del a #Deletes the dictionary ----> 2 print(a) NameError: name 'a' i
Comments (1)
Login to post a comment