Introduction
A dictionary in Python is an essential and robust built-in data structure that allows efficient retrieval of data by establishing a relationship between keys and values. It is an unordered collection of key-value pairs, where the values are stored under a specific key rather than in a particular order.
In this article, we will take a look at different approaches for accessing keys and values in dictionaries. We will review illustrative examples and discuss the appropriate contexts for each approach.
A Brief Anatomy of a Dictionary
What Is a Dictionary in Python?
You can visualize a Python dictionary by thinking about traditional physical dictionaries. The dictionary's key
is similar to a word that we would like to search for, and the value
is like the corresponding definition of the word in the dictionary. In terms of Python's data structures, dictionaries are containers that can hold other objects. Unlike ordered or indexed sequences (such as lists), dictionaries are mappings that assign a distinct name or key
to each element.
Building Blocks of a Dictionary
A key in a dictionary serves as a unique identifier that allows us to locate specific information. Keys can be of any immutable type (e.g., strings, numbers, tuples). The data associated with each key is called a value
, and can be mutable.
Any data type, such as a string, number, list, or even another dictionary, is an acceptable value
. The combination of these key-value pairs is represented in the form of tuples, known as dictionary items
. Together, these keys, values, and items collectively form the core structure of a dictionary. Let's explore how we can retrieve these elements.
To illustrate this, let's first construct a simple address book dictionary. The keys represent names of individuals, and the corresponding values contain their associated shipping addresses. We can construct it as below:
address_book = {
"Alicia Johnson": "123 Main Street, Cityville",
"Jerry Smith": "456 Corner Avenue, Townsville",
"Michael Jonas": "789 End Lane, Villageville"
}
We can visualize the structure of our simple dictionary as below:
Get Keys in a Dictionary
Key Retrieval Using the keys() Method
The keys()
method of a dictionary returns a list-like object containing all the keys of the dictionary. We can call this method on our address_book
as below:
address_keys = address_book.keys()
print(address_keys)
This gives us:
dict_keys(['Alicia Johnson', 'Jerry Smith', 'Michael Jonas'])
The output returned above is a dict_keys
object containing the keys of the address_book
dictionary. The advantage of this method is that we can further iterate over the dict_keys
object, convert it into a list, or use it in any other manner to access the individual keys. For example, let's utilize the keys we've extracted to find the first name of each person:
for k in address_keys:
print(k.split()[0]) # Split by space separator and return only the first string
And we get:
Alicia
Jerry
Michael
Key Retrieval Using the in
Operator
Dictionaries in Python support iteration, which means that we can loop over their elements and test membership using the in
operator. This versatile approach returns each key individually, rather than in a list-like object.
Let's use a simple for-loop
and the in
operator as an alternative way to return the keys of the dictionary:
for k in address_book:
print(k)
We get a similar output as above:
Alicia Johnson
Jerry Smith
Michael Jonas
Here, the expression k in address_book
searches for a key in the dictionary, not an index or a value. Note that dictionaries don't preserve the order of the pairs, so don't rely on item order when looping over dictionaries.
How to Get Values in a Dictionary
Now that we've seen how to retrieve dictionary keys, let's see some of the different approaches to get the corresponding values from our dictionary.
Retrieve Value by Key Using Square Brackets
Values in a dictionary are directly accessible by their respective keys. Since each key relates to exactly one value, we can access values using the square-brackets operator on the dictionary object.
For instance, let's try to find Jerry Smith's address:
print(address_book['Jerry Smith'])
We get their address as below:
456 Corner Avenue, Townsville
Retrieve Value Using get() Method
A major drawback of the square brackets operator we used above is that it returns a KeyError
when we try to access an item not present in the dictionary. For example, let's look for the non-existent customer "Brita Philips":
print(address_book['Brita Philips'])
We receive an error as below:
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
print(address_book['Brita Philips'])
KeyError: 'Brita Philips'
To avoid this, we can use the get()
method, which returns the value if it exists in the dictionary, and a default value otherwise. Let's try:
print(address_book.get('Brita Philips'))
The output is cleaner now, returning None
instead of a KeyError
:
None
If you'd like to return any other default value instead of None
, you can specify your own:
print(address_book.get('Brita Philips', 'Not a person'))
And we get:
Not a person
Value Retrieval Using the values() Method
The values()
method returns a list-like object which contains the values of the dictionary. For instance:
print(address_book.values())
This gives us:
dict_values(['123 Main Street, Cityville', '456 Corner Avenue, Townsville', '789 End Lane, Villageville'])
As you may have already guessed, it is possible to further iterate over the returned dict_values
object. You may also have noticed that there is no convenient method for getting the key from a value. This is because it is entirely possible to have duplicate values, whereas keys must be unique within a dictionary.
Get Key-Value Pairs from a Dictionary Simultaneously
We often need to retrieve the complete key-value pair (called item
) from a dictionary. There are a few different ways to do so.
Key-Value Retrieval Using the items() Method
The items()
method returns a list-like iterable object which yields each key-value pair as a tuple. Each returned item is of the form (key, value)
.
In our example, this is as below:
print(address_book.items())
This gives us:
dict_items([('Alicia Johnson', '123 Main Street, Cityville'), ('Jerry Smith', '456 Corner Avenue, Townsville'), ('Michael Jonas', '789 End Lane, Villageville')])
Using a For Loop with the items() Method
The items()
method gave us a dict_items
object in the above example. We can further unpack each pair using a for
statement as below:
for key, value in address_book.items():
print(key, "=>", value)
This yields:
Alicia Johnson => 123 Main Street, Cityville
Jerry Smith => 456 Corner Avenue, Townsville
Michael Jonas => 789 End Lane, Villageville
List Comprehension with Tuple Unpacking for Dictionary Items
Using list comprehension is an efficient way to return both the key and the value together in a single operation without the need to look up the key separately.
For example:
addresses = [key + " => " + value for key, value in address_book.items()]
print(addresses)
We get:
['Alicia Johnson => 123 Main Street, Cityville', 'Jerry Smith => 456 Corner Avenue, Townsville', 'Michael Jonas => 789 End Lane, Villageville']
To learn more about dictionary comprehension, you can read our guide to dictionary comprehension in Python.
### Conclusion
Retrieving keys and values from Python dictionaries is a widely-used and fundamental operation in data handling. We have seen that dictionaries are an incredibly efficient and versatile way of checking for key membership. This article has provided an overview of different methods to extract keys, values, and pairs from dictionaries.