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:
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:
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.
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.
Hence, Python dictionaries offer a flexible and efficient way to handle and manipulate data.