Python Dictionaries

PythonBeginner
Practice Now

Introduction

In Python, a dictionary is an ordered (since Python 3.7) collection of key: value pairs. Dictionaries are used to store data values in a way that is mutable, indexed, and does not allow duplicate keys. The main operations on a dictionary are storing a value with a key and extracting the value given the key.

For example, you can create a dictionary to store information about a cat:

## Dictionary: collection of key-value pairs
my_cat = {
    'size': 'fat',          ## key: 'size', value: 'fat'
    'color': 'gray',        ## key: 'color', value: 'gray'
    'disposition': 'loud'   ## key: 'disposition', value: 'loud'
}

In this lab, you will learn how to create dictionaries, access and modify their data, iterate over them, and use various utility methods to work with them effectively.

Accessing and Modifying Dictionary Data

In this step, you will learn how to create a dictionary, add new key-value pairs, update existing ones, and retrieve values using the subscript operator [].

You can add or update a dictionary entry by assigning a value to a key using the [] operator. If the key already exists, its value is updated. If the key does not exist, a new key-value pair is added.

Note: If you are not familiar with using WebIDE (VS Code like), please learn it first at this lab.

Let's start by creating a file to write our code.

First, open the main.py file located in the ~/project directory from the file explorer on the left.

Now, add the following code to main.py. This code defines a dictionary and then adds a new key-value pair to it.

## Add or update dictionary entry using subscript operator
my_cat = {
 'size': 'fat',
 'color': 'gray',
 'disposition': 'loud',
}
my_cat['age_years'] = 2  ## Add new key-value pair
print(my_cat)

To run the script, open a terminal and execute the following command:

python3 main.py

You should see the updated dictionary printed to the console:

{'size': 'fat', 'color': 'gray', 'disposition': 'loud', 'age_years': 2}

You can also retrieve a value by using the key inside the subscript operator []. Let's modify the main.py file to access and print the value associated with the 'size' key.

Replace the content of main.py with the following code:

my_cat = {
 'size': 'fat',
 'color': 'gray',
 'disposition': 'loud',
}
print(my_cat['size'])

Run the script again:

python3 main.py

The output will be the value of the 'size' key:

fat

Be aware that if you try to access a key that is not in the dictionary, Python will raise a KeyError. Let's see this in action. Replace the code in main.py with this:

my_cat = {
 'size': 'fat',
 'color': 'gray',
 'disposition': 'loud',
}
print(my_cat['eye_color'])

Run the script:

python3 main.py

This will result in a KeyError because the key 'eye_color' does not exist in the my_cat dictionary.

Traceback (most recent call last):
  File "/home/labex/project/main.py", line 5, in <module>
    print(my_cat['eye_color'])
KeyError: 'eye_color'

For the verification, please revert main.py to the first example that adds a new key and prints the whole dictionary.

## Add or update dictionary entry using subscript operator
my_cat = {
 'size': 'fat',
 'color': 'gray',
 'disposition': 'loud',
}
my_cat['age_years'] = 2  ## Add new key-value pair
print(my_cat)

Iterating Over Dictionaries

In this step, you will explore different ways to loop through a dictionary. Python provides several methods to iterate over a dictionary's keys, values, or both.

Iterating Over Values with values()

The values() method returns a view object that displays a list of all the values in the dictionary. You can loop through this object to access each value.

Clear the main.py file and add the following code:

## Iterate over dictionary values using .values() method
pet = {'color': 'red', 'age': 42}
for value in pet.values():  ## Loop through all values
    print(value)

Run the script:

python3 main.py

The output will show each value on a new line:

red
42

Iterating Over Keys with keys()

Similarly, the keys() method returns a view object containing the dictionary's keys. While you can use pet.keys(), iterating directly over the dictionary itself is the more common and Pythonic way to loop through its keys.

Update main.py with the following code:

## Iterating over dictionary directly loops through keys (default behavior)
pet = {'color': 'red', 'age': 42}
for key in pet:  ## Equivalent to for key in pet.keys()
    print(key)

Run the script:

python3 main.py

You will see the keys printed:

color
age

Iterating Over Key-Value Pairs with items()

The items() method is very useful when you need both the key and the value during iteration. It returns a view object where each item is a (key, value) tuple.

Update main.py to use items():

## Iterate over key-value pairs using .items() method
pet = {'color': 'red', 'age': 42}
for key, value in pet.items():  ## Unpack tuple into key and value
    print(f'Key: {key} Value: {value}')

Here, we are using tuple unpacking (for key, value in ...) to assign the first element of the tuple to key and the second to value in each iteration.

Run the script:

python3 main.py

The output will be formatted strings showing each key-value pair:

Key: color Value: red
Key: age Value: 42

Safely Accessing and Adding Items

In this step, you will learn how to safely retrieve values without causing a KeyError and how to add items conditionally.

Safely Accessing with get()

As you saw in Step 1, trying to access a non-existent key with [] raises a KeyError. The get() method provides a safer way to access keys. It returns the value for a key if it exists, but if it doesn't, it returns None instead of raising an error.

Clear main.py and add the following code:

## .get() method: safely retrieve value, returns None if key doesn't exist
wife = {'name': 'Rose', 'age': 33}

print(f'My wife name is {wife.get("name")}')
print(f'She is deeply in love with {wife.get("husband")}')

Run the script:

python3 main.py

The output shows that get() returned the value for 'name' and None for the missing key 'husband':

My wife name is Rose
She is deeply in love with None

You can also provide a default value to get() as a second argument. This value will be returned if the key is not found.

Modify main.py to provide a default value:

wife = {'name': 'Rose', 'age': 33}

print(f'She is deeply in love with {wife.get("husband", "lover")}')

Run it again:

python3 main.py

Now the output uses your custom default value:

She is deeply in love with lover

Conditionally Adding with setdefault()

The setdefault() method offers a concise way to add a key-value pair only if the key does not already exist. It checks for the key; if it's present, it returns the key's value. If it's not, it inserts the key with the specified value and returns that value.

Update main.py to use setdefault():

wife = {'name': 'Rose', 'age': 33}
wife.setdefault('has_hair', True) ## 'has_hair' does not exist, so it's added.
wife.setdefault('name', 'Lily') ## 'name' exists, so the dictionary is not changed.
print(wife)

Run the script:

python3 main.py

The output shows that 'has_hair' was added, but the value for 'name' was not updated:

{'name': 'Rose', 'age': 33, 'has_hair': True}

Removing Items from a Dictionary

In this step, you will practice various methods for removing items from a dictionary.

Removing with pop()

The pop() method removes an item with the specified key and returns its value. If the key is not found, it raises a KeyError unless a default value is provided.

Clear main.py and add the following code to see pop() in action:

wife = {'name': 'Rose', 'age': 33, 'hair': 'brown'}
removed_value = wife.pop('age')
print(f"Removed value: {removed_value}")
print(wife)

Run the script:

python3 main.py

The output shows the removed value and the dictionary after removal:

Removed value: 33
{'name': 'Rose', 'hair': 'brown'}

Removing with popitem()

The popitem() method removes the last inserted item in a dictionary (in Python 3.7+). It returns the removed item as a (key, value) tuple.

Modify main.py to use popitem():

wife = {'name': 'Rose', 'age': 33, 'hair': 'brown'}
removed_item = wife.popitem()
print(f"Removed item: {removed_item}")
print(wife)

Run the script:

python3 main.py

The last item, ('hair', 'brown'), is removed and printed:

Removed item: ('hair', 'brown')
{'name': 'Rose', 'age': 33}

Removing with the del Keyword

The del keyword can be used to remove an item by its key. It does not return the value of the removed item.

Modify main.py to use del:

wife = {'name': 'Rose', 'age': 33, 'hair': 'brown'}
del wife['age']
print(wife)

Run the script:

python3 main.py

The dictionary is printed without the 'age' key:

{'name': 'Rose', 'hair': 'brown'}

Removing All Items with clear()

The clear() method removes all items from a dictionary, leaving it empty.

Modify main.py to use clear():

wife = {'name': 'Rose', 'age': 33, 'hair': 'brown'}
wife.clear()
print(wife)

Run the script:

python3 main.py

The output is an empty dictionary:

{}

For the verification, please ensure your main.py uses pop() to remove the 'age' key and prints the final dictionary.

wife = {'name': 'Rose', 'age': 33, 'hair': 'brown'}
wife.pop('age')
print(wife)

Dictionary Utility Operations

In this step, you will discover some useful dictionary utilities, including checking for the existence of keys and values, pretty-printing, and merging dictionaries.

Checking for Keys and Values with in

You can use the in operator to check if a key exists in a dictionary.

Clear main.py and add this code:

person = {'name': 'Rose', 'age': 33}

print(f"'name' in person: {'name' in person}")
print(f"'height' in person: {'height' in person}")

Run the script:

python3 main.py

The output shows True for an existing key and False for a non-existing one:

'name' in person: True
'height' in person: False

You can also use in with the values() method to check if a value exists in the dictionary.

Modify main.py:

person = {'name': 'Rose', 'age': 33}

print(f"'Rose' in person.values(): {'Rose' in person.values()}")
print(f"33 in person.values(): {33 in person.values()}")
print(f"'John' in person.values(): {'John' in person.values()}")

Run it:

python3 main.py

Output:

'Rose' in person.values(): True
33 in person.values(): True
'John' in person.values(): False

Pretty Printing with pprint

When dictionaries are large, printing them directly can result in a long, hard-to-read line. The pprint module provides a "pretty-print" capability to format them in a more readable way.

Update main.py:

import pprint

wife = {'name': 'Rose', 'age': 33, 'has_hair': True, 'hair_color': 'brown', 'height': 1.6, 'eye_color': 'brown'}
pprint.pprint(wife)

Run the script:

python3 main.py

The output is neatly formatted, with keys sorted alphabetically:

{'age': 33,
 'eye_color': 'brown',
 'hair_color': 'brown',
 'has_hair': True,
 'height': 1.6,
 'name': 'Rose'}

Merging Dictionaries

You can merge two dictionaries using the dictionary unpacking operator ** (available in Python 3.5+). If there are overlapping keys, the value from the second dictionary will be used.

Update main.py with the following code:

dict_a = {'a': 1, 'b': 2}
dict_b = {'b': 3, 'c': 4}
dict_c = {**dict_a, **dict_b}
print(dict_c)

Run the script:

python3 main.py

The output is a new dictionary containing all items from both. Note that the value for key 'b' is 3, which comes from dict_b.

{'a': 1, 'b': 3, 'c': 4}

Summary

Congratulations on completing this lab on Python dictionaries!

In this lab, you have learned the fundamental operations for working with one of Python's most powerful data structures. You covered:

  • Creating, Accessing, and Modifying: Using {} to create dictionaries and the subscript operator [] to add, update, and retrieve data.
  • Iteration: Looping through keys, values, and key-value pairs using the keys(), values(), and items() methods.
  • Safe Operations: Using get() to avoid KeyError and setdefault() to add items conditionally.
  • Removing Items: Using pop(), popitem(), the del keyword, and clear() to remove items.
  • Utility Operations: Checking for membership with the in operator, formatting output with pprint, and merging dictionaries with the ** unpacking operator.

Mastering dictionaries is a crucial step in becoming a proficient Python programmer. Keep practicing these concepts to build more complex and efficient applications.