4.4 Dictionaries: Key-Value Pairs

A dictionary in Python is a collection of key-value pairs where each key is associated with a value. Dictionaries are unordered, mutable, and indexed by keys, which must be unique and immutable (such as strings, numbers, or tuples). Unlike lists and tuples, which are indexed by a range of integers, dictionaries use keys to retrieve values, making them ideal for cases where you need to associate data with specific identifiers.

In this section, we will explore how to create dictionaries, access and modify their elements, and use common dictionary operations and methods.


4.4.1 Creating Dictionaries

You can create a dictionary by placing comma-separated key-value pairs inside curly braces {}. Alternatively, you can use the dict() function to create a dictionary.

Syntax:

my_dict = {
    key1: value1,
    key2: value2,
    key3: value3,
    ...
}
# OR
my_dict = dict(key1=value1, key2=value2, key3=value3)

Examples:

An empty dictionary:

empty_dict = {}

Using the dict() function to create a dictionary:

person = dict(name="Alice", age=25, profession="Engineer")

A dictionary with mixed key types:

mixed_dict = {1: "one", "two": 2, 3.0: [1, 2, 3]}

A dictionary with string keys and integer values:

student_ages = {"Alice": 25, "Bob": 22, "Charlie": 27}

4.4.2 Accessing Dictionary Values

You can access the value associated with a key using square brackets []. If the key does not exist in the dictionary, Python raises a KeyError. You can avoid this error by using the get() method, which returns None (or a specified default value) if the key is not found.

Syntax:

value = dict_name[key]
# OR using the get() method
value = dict_name.get(key, default_value)

Examples:

Using the get() method:

print(student_ages.get("Bob"))  # Output: 22
print(student_ages.get("Eve", "Not found"))  # Output: Not found

Accessing values using keys:

student_ages = {"Alice": 25, "Bob": 22, "Charlie": 27}
print(student_ages["Alice"])  # Output: 25

4.4.3 Modifying Dictionaries

Dictionaries are mutable, so you can modify, add, or remove key-value pairs.

4.4.3.1 Adding or Updating Key-Value Pairs

You can add new key-value pairs or update existing values by assigning a value to a key.

Example:

student_ages = {"Alice": 25, "Bob": 22}

# Adding a new key-value pair
student_ages["Charlie"] = 27

# Updating an existing value
student_ages["Alice"] = 26

print(student_ages)  # Output: {'Alice': 26, 'Bob': 22, 'Charlie': 27}

4.4.3.2 Removing Key-Value Pairs

You can remove key-value pairs using the del statement or the pop() method:

  • del removes the key-value pair, raising a KeyError if the key does not exist.
  • pop() removes the key-value pair and returns the value. If the key does not exist, it raises a KeyError, but you can provide a default value.

Example with del:

del student_ages["Bob"]
print(student_ages)  # Output: {'Alice': 26, 'Charlie': 27}

Example with pop():

age = student_ages.pop("Alice")
print(age)  # Output: 26
print(student_ages)  # Output: {'Charlie': 27}

4.4.3.3 Clearing the Dictionary

You can remove all key-value pairs using the clear() method.

Example:

student_ages.clear()
print(student_ages)  # Output: {}

4.4.4 Dictionary Operations

Python provides several built-in operations for working with dictionaries.

4.4.4.1 Checking Key Membership

You can check whether a key exists in a dictionary using the in and not in operators.

Example:

student_ages = {"Alice": 25, "Bob": 22}
print("Alice" in student_ages)  # Output: True
print("Eve" not in student_ages)  # Output: True

4.4.4.2 Dictionary Length

You can find the number of key-value pairs in a dictionary using the len() function.

Example:

print(len(student_ages))  # Output: 2

4.4.5 Iterating Over Dictionaries

You can iterate over a dictionary’s keys, values, or key-value pairs using loops.

4.4.5.1 Iterating Over Keys

Example:

student_ages = {"Alice": 25, "Bob": 22, "Charlie": 27}

for key in student_ages:
    print(key)

Output:

Alice
Bob
Charlie

4.4.5.2 Iterating Over Values

Example:

for value in student_ages.values():
    print(value)

Output:

25
22
27

4.4.5.3 Iterating Over Key-Value Pairs

You can iterate over both keys and values using the items() method.

Example:

for key, value in student_ages.items():
    print(f"{key} is {value} years old.")

Output:

Alice is 25 years old.
Bob is 22 years old.
Charlie is 27 years old.

4.4.6 Dictionary Methods

Python dictionaries provide several useful methods for performing common operations.

copy(): Returns a shallow copy of the dictionary.

copied_dict = student_ages.copy()

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

new_students = {"David": 23, "Eve": 21}
student_ages.update(new_students)
print(student_ages)  # Output: {'Alice': 25, 'Bob': 22, 'Charlie': 27, 'David': 23, 'Eve': 21}

items(): Returns a view object of the dictionary’s key-value pairs.

print(student_ages.items())  # Output: dict_items([('Alice', 25), ('Bob', 22), ('Charlie', 27)])

values(): Returns a view object of the dictionary’s values.

print(student_ages.values())  # Output: dict_values([25, 22, 27])

keys(): Returns a view object of the dictionary’s keys.

print(student_ages.keys())  # Output: dict_keys(['Alice', 'Bob', 'Charlie'])

4.4.7 Nested Dictionaries

A nested dictionary is a dictionary where the values can also be dictionaries. This is useful for representing more complex data structures.

Example:

students = {
    "Alice": {"age": 25, "major": "Math"},
    "Bob": {"age": 22, "major": "Physics"},
    "Charlie": {"age": 27, "major": "Computer Science"}
}

# Accessing nested dictionary values
print(students["Alice"]["major"])  # Output: Math

In this example, each student's data is itself a dictionary containing attributes like age and major.


4.4.8 Use Cases for Dictionaries

  1. Storing Configuration or Settings:
    Dictionaries are

Counting Occurrences:
Dictionaries are often used to count occurrences of elements in a collection.Example:

text = "apple banana apple cherry cherry cherry"
word_counts = {}

for word in text.split():
    word_counts[word] = word_counts.get(word, 0) + 1

print(word_counts)  # Output: {'apple': 2, 'banana': 1, 'cherry': 3}

Mapping Keys to Values:
Dictionaries are ideal for associating unique keys with corresponding values, such as storing student information where the key is the student's name.Example:

capitals = {"USA": "Washington, D.C.", "France": "Paris", "Japan": "Tokyo"}

commonly used to store configurations or settings for applications.

Example:

config = {"theme": "dark", "language": "English", "timeout": 120}

4.4.9 Summary

  • Dictionaries are collections of key-value pairs, where keys are unique and immutable, and values can be any type.
  • You can create dictionaries using curly braces {} or the dict() function.
  • You can access, add, modify, or remove dictionary elements using keys, and dictionaries provide methods such as keys(), values(), items(), and update().
  • Nested dictionaries allow you to store more complex hierarchical data.
  • Dictionaries are ideal for mapping keys to values, counting occurrences, and storing configuration settings.

Understanding how to work with dictionaries is crucial for efficient data organization and retrieval in Python programs.