“Python: Retrieving Keys and Values from a Dictionary”


A dictionary in Python is a 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 discuss different approaches for accessing keys and values in dictionaries, with illustrative examples for each approach.

A Brief Anatomy of a Dictionary

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 include:

  • A key, which serves as a unique identifier that allows us to locate specific information. Keys can be of any immutable type (e.g., strings, numbers, tuples).
  • A value, which is the data associated with each key and can be mutable. Any data type such as a string, number, list, or even another dictionary is an acceptable value.
  • An item, which is the combination of a key-value pair and is represented in the form of tuples. These keys, values, and items together form the core structure of a dictionary.

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:

  "Alicia Johnson": "123 Main Street, Cityville",
  "Jerry Smith": "456 Corner Avenue, Townsville",
  "Michael Jonas": "789 End Lane, Villageville"

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()

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:

And we get:


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:

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.

Get Values in a 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:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
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:


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:


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:


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()]

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.


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.

Source link

Leave a Reply