Manage Dictionaries in Python

PythonBeginner
Practice Now

Introduction

In this lab, you will gain hands-on experience with Python dictionaries, an essential data structure for storing data as key-value pairs. You will learn how to create and inspect dictionaries, access and modify their elements, add and remove items, and work with dictionary view objects. By the end of this lab, you will be proficient in performing common dictionary operations.

Create and Inspect Dictionaries

In this step, you will learn how to create and inspect dictionaries. A dictionary is a collection of key-value pairs where each key must be unique. Dictionaries are created with curly braces {} or the dict() constructor. Since Python 3.7, dictionaries maintain the order in which items were inserted.

First, open the main.py file from the file explorer on the left side of the VS Code editor.

Add the following code to main.py. This script demonstrates various ways to create a dictionary.

## Create an empty dictionary using curly braces
empty_dict = {}
print(f"Empty dictionary: {empty_dict}")
print(f"Type of empty_dict: {type(empty_dict)}")

## Create a dictionary with initial key-value pairs
student_info = {'name': 'Alice', 'age': 25, 'major': 'Computer Science'}
print(f"\nStudent info: {student_info}")

## Create a dictionary using the dict() constructor with keyword arguments
student_info_kw = dict(name='Bob', age=22, major='Physics')
print(f"Student info (from keywords): {student_info_kw}")

## Create a dictionary from a list of key-value tuples
student_info_tuples = dict([('name', 'Charlie'), ('age', 28), ('major', 'Chemistry')])
print(f"Student info (from tuples): {student_info_tuples}")

After adding the code, save the file by pressing Ctrl + S.

Now, run the script by opening a terminal in the VS Code editor (Ctrl + ~) and executing the following command:

python main.py

You should see the following output, which shows the different dictionaries you created:

Empty dictionary: {}
Type of empty_dict: <class 'dict'>

Student info: {'name': 'Alice', 'age': 25, 'major': 'Computer Science'}
Student info (from keywords): {'name': 'Bob', 'age': 22, 'major': 'Physics'}
Student info (from tuples): {'name': 'Charlie', 'age': 28, 'major': 'Chemistry'}

This step has taught you the fundamental ways to create dictionaries in Python, both empty and with initial data.

Access and Modify Dictionary Elements

In this step, you will learn how to access and modify elements within a dictionary. You can retrieve a value by referencing its key inside square brackets [].

First, clear the previous content from main.py. Then, add the following code to the file. This script demonstrates how to access and modify dictionary data.

## Define a sample dictionary
student_info = {'name': 'Alice', 'age': 25, 'major': 'Computer Science'}
print(f"Original dictionary: {student_info}")

## Access elements using square brackets
student_name = student_info['name']
print(f"\nStudent Name: {student_name}")

## Using the get() method to access an element
student_age = student_info.get('age')
print(f"Student Age (using get()): {student_age}")

## The get() method can provide a default value if the key is not found
student_city = student_info.get('city', 'Not Specified')
print(f"Student City (with default): {student_city}")

## Modify the value of an existing key
print(f"\nOriginal age: {student_info['age']}")
student_info['age'] = 26
print(f"Modified age: {student_info['age']}")

print(f"\nUpdated dictionary: {student_info}")

Save the file (Ctrl + S) and run the script from the terminal:

python main.py

The output shows how to retrieve values and how the dictionary looks after a modification:

Original dictionary: {'name': 'Alice', 'age': 25, 'major': 'Computer Science'}

Student Name: Alice
Student Age (using get()): 25
Student City (with default): Not Specified

Original age: 25
Modified age: 26

Updated dictionary: {'name': 'Alice', 'age': 26, 'major': 'Computer Science'}

Note that using square brackets [] to access a non-existent key will raise a KeyError, while get() provides a safer way to access keys that may not exist.

Add and Delete Dictionary Elements

This step covers adding new elements to a dictionary and deleting existing ones. You can add a new key-value pair by assigning a value to a new key.

Replace the content of main.py with the following code. This script demonstrates the full lifecycle of dictionary elements: adding, updating, and removing them in various ways.

## Define a sample dictionary
student_info = {'name': 'Alice', 'age': 26, 'major': 'Computer Science'}
print(f"Initial dictionary: {student_info}")

## Add a new key-value pair
student_info['city'] = 'New York'
print(f"After adding 'city': {student_info}")

## Delete an element using pop()
## pop() removes the key and returns its value
removed_major = student_info.pop('major')
print(f"\nRemoved major: {removed_major}")
print(f"After pop('major'): {student_info}")

## Delete the last inserted element using popitem()
## popitem() removes and returns the (key, value) pair
removed_item = student_info.popitem()
print(f"\nRemoved item: {removed_item}")
print(f"After popitem(): {student_info}")

## Delete an element using the 'del' statement
del student_info['age']
print(f"\nAfter del student_info['age']: {student_info}")

## The clear() method removes all elements from the dictionary
student_info.clear()
print(f"After clear(): {student_info}")

Save the file (Ctrl + S) and run the script:

python main.py

The output will show the dictionary at each stage of modification:

Initial dictionary: {'name': 'Alice', 'age': 26, 'major': 'Computer Science'}
After adding 'city': {'name': 'Alice', 'age': 26, 'major': 'Computer Science', 'city': 'New York'}

Removed major: Computer Science
After pop('major'): {'name': 'Alice', 'age': 26, 'city': 'New York'}

Removed item: ('city', 'New York')
After popitem(): {'name': 'Alice', 'age': 26}

After del student_info['age']: {'name': 'Alice'}
After clear(): {}

In this step, you have learned how to add new elements and how to remove them using pop(), popitem(), del, and clear().

Explore Dictionary View Objects

In this step, you will explore dictionary view objects. These are dynamic objects that provide a view of a dictionary's keys, values, or items. Any changes to the dictionary are immediately reflected in the view.

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

## Define a sample dictionary
student_info = {'name': 'Alice', 'age': 26, 'major': 'Computer Science'}
print(f"Original dictionary: {student_info}\n")

## Get the view objects
keys_view = student_info.keys()
values_view = student_info.values()
items_view = student_info.items()

print(f"Keys View: {keys_view}")
print(f"Values View: {values_view}")
print(f"Items View: {items_view}")

## Views are dynamic and reflect dictionary changes
print("\n--- Modifying Dictionary ---")
student_info['city'] = 'New York'
print(f"Dictionary after adding 'city': {student_info}")
print(f"Keys View after modification: {keys_view}")
print(f"Values View after modification: {values_view}")

## You can iterate over view objects
print("\n--- Iterating over Keys View ---")
for key in keys_view:
    print(key)

## You can convert views to other data types like lists
keys_list = list(keys_view)
print(f"\nKeys view converted to a list: {keys_list}")

Save the file (Ctrl + S) and run the script:

python main.py

The output demonstrates the creation, dynamic nature, and iteration of view objects:

Original dictionary: {'name': 'Alice', 'age': 26, 'major': 'Computer Science'}

Keys View: dict_keys(['name', 'age', 'major'])
Values View: dict_values(['Alice', 26, 'Computer Science'])
Items View: dict_items([('name', 'Alice'), ('age', 26), ('major', 'Computer Science')])

--- Modifying Dictionary ---
Dictionary after adding 'city': {'name': 'Alice', 'age': 26, 'major': 'Computer Science', 'city': 'New York'}
Keys View after modification: dict_keys(['name', 'age', 'major', 'city'])
Values View after modification: dict_values(['Alice', 26, 'Computer Science', 'New York'])

--- Iterating over Keys View ---
name
age
major
city

Keys view converted to a list: ['name', 'age', 'major', 'city']

This step has shown you how to use keys(), values(), and items() to get dynamic views of a dictionary's contents, which is useful for many programming tasks.

Summary

In this lab, you gained practical experience with Python dictionaries. You started by creating dictionaries using curly braces {} and the dict() constructor. You then learned to access and modify dictionary elements using square bracket notation [] and the get() method. Next, you practiced adding new key-value pairs and removing them with various methods, including pop(), popitem(), the del statement, and clear(). Finally, you explored dynamic dictionary views (keys(), values(), and items()), understanding how they reflect changes in the dictionary and how to iterate over them.