How To Use Dictionary In Python

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:

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:

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.

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 [].

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.

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.

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.

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:

Output:

{'The Shawshank Redemption': 9.3, 'The Godfather': 9.2, 'The Dark Knight': 9.0}

Full Code

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!