Dictionary Definition

A dictionary in Python is a mutable and dynamic data structure that stores a collection of unique key-value pairs. Dictionaries are often used for data manipulation, organization, and retrieval because of their efficiency with respect to lookup operations.

Understanding Dictionaries

A dictionary in Python is defined by enclosing a comma-separated list of key:value pairs within curly braces {}. The keys are unique within a dictionary while the values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.

Here’s an example of a dictionary:

1student = {
2    "name": "John Doe",
3    "age": 20,
4    "courses": ["Math", "Science"],
5}

In this dictionary, name, age, and courses are keys while John Doe, 20, and Math, Science are the corresponding values.

Accessing Dictionary Values

Values in a dictionary can be accessed by their corresponding keys. To do this, you place the key inside square brackets [] immediately after the name of the dictionary.

If we want to access the name in our student dictionary, we can do it like this:

1print(student['name']) # It will output 'John Doe'

Note

Attempting to access a key that does not exist in the dictionary will result in a KeyError.

We can avoid this by using the dictionary’s get method, which returns None if the key does not exist, or defaults to a value of your choice.

1print(student.get('grade', 'Not Found')) # It will output 'Not Found'

Modifying Dictionaries

Dictionaries are mutable, meaning you can change their content without changing their identity.

You can modify a dictionary by adding a new entry or key-value pair, modifying an existing entry, or removing an existing entry as shown below.

 1# add an entry
 2student['grade'] = 85
 3
 4# modify an existing entry
 5student['name'] = "Jane Doe"
 6
 7# remove an entry
 8del student['age']
 9
10print(student)
11# It will output {'name': 'Jane Doe', 'courses': ['Math', 'Science'], 'grade': 85}

Hence, Python dictionaries offer a flexible and efficient way to handle and manipulate data.