One of the most essential and important data structures in Python is that of the dictionary. A dictionary in Python is quite similar to a real-world dictionary, as it stores key-value pairs that can be used to store, access, and manage data.
This tutorial will guide you through the creation and utilization of dictionaries in Python and help you manipulate and understand the data more effectively.
Creating a Dictionary
To create a dictionary, you need to place a set of key-value pairs within curly braces {}
. Each key-value pair is separated by a colon (:)
, and each pair is separated by a comma (,)
. An example of a dictionary looks like this:
1 2 3 4 5 |
movie_ratings = { "The Shawshank Redemption": 9.3, "The Godfather": 9.2, "Pulp Fiction": 8.9 } |
In this example, movie titles are the keys and their corresponding ratings are the values.
Accessing Values in a Dictionary
You can access the value associated with a given key using the square brackets []
and passing the desired key. If the key does not exist in the dictionary, a KeyError will be raised. Here’s an example:
1 2 |
rating_shawshank = movie_ratings["The Shawshank Redemption"] print(rating_shawshank) |
Output:
9.3
To avoid KeyError when accessing values, you can use the get()
method. It returns None
by default if the key is not found. However, you can also provide a default value as the second argument to the get()
method.
1 2 |
rating_not_found = movie_ratings.get("Non-Existent Movie", "Not Found") print(rating_not_found) |
Output:
Not Found
Adding and Updating Key-Value Pairs
To add a new key-value pair or update an existing one, you can use the assignment operator =
along with the key in square brackets []
.
1 2 3 4 |
movie_ratings["The Dark Knight"] = 9.0 movie_ratings["The Godfather"] = 9.3 print(movie_ratings) |
Output:
{'The Shawshank Redemption': 9.3, 'The Godfather': 9.3, 'Pulp Fiction': 8.9, 'The Dark Knight': 9.0}
Removing Key-Value Pairs
The del
keyword can be used to remove a specific key-value pair from the dictionary.
1 2 |
del movie_ratings["Pulp Fiction"] print(movie_ratings) |
Output:
{'The Shawshank Redemption': 9.3, 'The Godfather': 9.3, 'The Dark Knight': 9.0}
Looping through a Dictionary
You can use a for
loop to iterate over the keys, values, or items (key-value pairs) in a dictionary.
1 2 |
for key in movie_ratings: print(key) |
Output:
The Shawshank Redemption The Godfather The Dark Knight
You can also use the keys()
, values()
, and items()
methods to loop through specific parts of the dictionary.
1 2 |
for key, value in movie_ratings.items(): print(key, value) |
Output:
The Shawshank Redemption 9.3 The Godfather 9.3 The Dark Knight 9.0
Dictionary Comprehension
Dictionary comprehension is an elegant and concise way to create a new dictionary from an existing iterable, such as a list or another dictionary.
Here’s an example:
1 2 3 4 5 6 |
movies = ["The Shawshank Redemption", "The Godfather", "The Dark Knight"] ratings = [9.3, 9.2, 9.0] new_movie_ratings = {key: value for key, value in zip(movies, ratings)} print(new_movie_ratings) |
Output:
{'The Shawshank Redemption': 9.3, 'The Godfather': 9.2, 'The Dark Knight': 9.0}
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
movie_ratings = { "The Shawshank Redemption": 9.3, "The Godfather": 9.2, "Pulp Fiction": 8.9 } rating_shawshank = movie_ratings["The Shawshank Redemption"] print(rating_shawshank) rating_not_found = movie_ratings.get("Non-Existent Movie", "Not Found") print(rating_not_found) movie_ratings["The Dark Knight"] = 9.0 movie_ratings["The Godfather"] = 9.3 print(movie_ratings) del movie_ratings["Pulp Fiction"] print(movie_ratings) for key in movie_ratings: print(key) for key, value in movie_ratings.items(): print(key, value) movies = ["The Shawshank Redemption", "The Godfather", "The Dark Knight"] ratings = [9.3, 9.2, 9.0] new_movie_ratings = {key: value for key, value in zip(movies, ratings)} print(new_movie_ratings) |
Conclusion
Now you have a solid understanding of how dictionaries work in Python and how to create, access, update, and iterate through them. Using dictionaries effectively will help you better store, manage and access data in your Python programs. Happy coding!