Skip to content

8.4 Dictionaries

8.4a What are Python dictionaries?

A dictionary in Python is a collection of key-value pairs. Each key is unique and maps to a value. Dictionaries are mutable, meaning you can change their content by adding, removing, or updating key-value pairs. They are unordered until Python 3.7, where they maintain insertion order.

 


 

8.4b Why do we use Python dictionaries?

Dictionaries are used for various reasons:

  • Fast Lookup - Dictionaries allow for fast retrieval of values when you know the key.
  • Data Organization - They help in organizing data into key-value pairs, which is more readable and logical.
  • Flexible Data Storage - They can store any data type (numbers, strings, lists, other dictionaries, etc.) as values.

 


 

8.4c How do we use Python dictionaries?

 

  • How do we create a dictionary?

Example 8.4.1 - Creating a dictionary.

# Creating an empty dictionary
my_dict = {}

# Creating a dictionary with initial key-value pairs
student = {
    'name': 'Alice',
    'age': 21,
    'major': 'Computer Science'
}

 

  • How do we access an item from a dictionary?

Example 8.4.2 - Accessing items from a dictionary.

student = {
    'name': 'Alice',
    'age': 21,
    'major': 'Computer Science'
}

# Accessing a value by key
name = student['name']
print(f"Name: {name}")

# Using get() method to access value
age = student.get('age')
print(f"Age: {age}")

Example 8.4.2 - Output

Name: Alice
Age: 21

 

  • How do we add or update an item in a dictionary?

Example 8.4.3 - Adding or updating items.

student = {
    'name': 'Alice',
    'age': 21,
    'major': 'Computer Science'
}

# Adding a new key-value pair
student['GPA'] = 3.8

# Updating an existing key-value pair
student['age'] = 22

 

  • How do we remove an item from a dictionary?

Example 8.4.4 - Removing items.

student = {
    'name': 'Alice',
    'age': 22,
    'major': 'Computer Science',
    'GPA': '3.8'
}

# Using pop() method to remove an item by key and return its value
major = student.pop('major')
print(f"Major: {major}")

# Using del statement to remove an item by key
del student['GPA']

Example 8.4.4 - Output

Major: Computer Science

 


 

8.4d Useful dictionary functions

 

  • keys() - Returns a view object containing the keys of the dictionary.

Example 8.4.5 - keys()

student = {
    'name': 'Alice',
    'age': 22,
}

keys = student.keys()
print(keys)

Example 8.4.5 - Output

dict_keys(['name', 'age'])

 

  • values() - Returns a view object containing the values of the dictionary.

Example 8.4.6 - values()

student = {
    'name': 'Alice',
    'age': 22,
}

values = student.values()
print(values)

Example 8.4.6 - Output

dict_values(['Alice', 22])

 

  • items() - Returns a view object containing the key-value pairs of the dictionary.

Example 8.4.7 - items()

student = {
    'name': 'Alice',
    'age': 22,
}

items = student.items()
print(items)

Example 8.4.7 - Output

dict_items([('name', 'Alice'), ('age', 22)])

 

  • clear() - Removes all items from the dictionary.

Example 8.4.8 - clear()

student = {
    'name': 'Alice',
    'age': 22,
}


student.clear()
print(student)

Example 8.4.8 - Output

{}

 

  • update() - Updates the dictionary with elements from another dictionary or an iterable of key-value pairs.

Example 8.4.9 - update()

student.update({'name': 'Bob', 'age': 25})
print(student)

Example 8.4.9 - Output

{'name': 'Bob', 'age': 25}

 


 

8.4d - Looping over dictionary items

 

  • Looping through keys

Example 8.4.10

student = {'name': 'Alice', 'age': 21, 'major': 'Computer Science'}

for key in student.keys():
    print(f"Key: {key}")
Example 8.4.10 - Output

Key: name
Key: age
Key: major

 

  • Looping through values

Example 8.4.11

student = {'name': 'Alice', 'age': 21, 'major': 'Computer Science'}

for value in student.values():
    print(f"Value: {value}")
Example 8.4.11 - Output

Value: Alice
Value: 21
Value: Computer Science

 

  • Looping through key-value pairs

Example 8.4.12

student = {'name': 'Alice', 'age': 21, 'major': 'Computer Science'}

for key, value in student.items():
    print(f"Key: {key}, Value: {value}")

Example 8.4.12 - Output

Key: name, Value: Alice
Key: age, Value: 21
Key: major, Value: Computer Science

 


 

Note

Python dictionaries are collections of key-value pairs that are used for organizing and managing data efficiently. They allow for fast lookups, flexible data storage, and logical data organization. Some of the useful functions for dictionaries include keys(), values(), items(), clear(), and update(). Accessing items can be done using keys directly or with the get() method. Looping over dictionary items can be done through their keys, values, or key-value pairs.

 


 

8.4e Develop a program using dictionaries as data structures

Exercise 8.4.1 - Given the following dictionary that contains the names and ages of a group of friends:

friends = {
    'Alice': 23,
    'Bob': 25,
    'Charlie': 22,
    'Daisy': 24
}

Perform the following tasks:

  • Add a new friend to the dictionary: 'Eve', who is 26 years old.
  • Update the age of 'Charlie' to 23.
  • Remove 'Daisy' from the dictionary.
  • Print all the names (keys) of the friends.
  • Print all the ages (values) of the friends.
  • Print each friend's name along with their age using a loop.

Write the complete program and show the output for each step.

Exercise 8.4.1 - Model Answer - Make sure to work out the exercise before checking the model answer.