Skip to Content
Course content

3.3.1 Key-value pairs and dictionary operations

In Python, dictionaries are a collection of key-value pairs. Each element in a dictionary consists of a key, which is unique, and a corresponding value. Dictionaries are used to store data in an efficient way that allows fast lookups by key.

1. Key-Value Pairs

A key-value pair is a combination where:

  • Key: A unique identifier for a value. Keys are immutable data types such as strings, numbers, or tuples.
  • Value: The data associated with a key. The value can be of any data type, including another dictionary, list, string, etc.

Example of a dictionary with key-value pairs:

person = {
    "name": "Alice",  # "name" is the key, and "Alice" is the value
    "age": 25,        # "age" is the key, and 25 is the value
    "city": "New York" # "city" is the key, and "New York" is the value
}

Here, "name", "age", and "city" are the keys, and "Alice", 25, and "New York" are the values.

2. Dictionary Operations

Python provides several operations to interact with dictionaries, including accessing, modifying, adding, and removing key-value pairs. Below are the common operations:

Accessing Values

To retrieve a value from a dictionary, use its key in square brackets or the get() method.

Example:

# Accessing value using the key
print(person["name"])  # Output: Alice

# Using get() method
print(person.get("age"))  # Output: 25
  • The square bracket method will raise a KeyError if the key does not exist.
  • The get() method will return None (or a default value if provided) if the key does not exist.

Modifying and Adding Key-Value Pairs

You can modify existing key-value pairs by assigning new values to existing keys. You can also add new key-value pairs by specifying a new key.

Example:

# Modifying an existing value
person["age"] = 26

# Adding a new key-value pair
person["email"] = "alice@example.com"

Removing Key-Value Pairs

There are several ways to remove elements from a dictionary:

  • del: Removes the key-value pair by key.
  • pop(): Removes the key-value pair and returns the value associated with the key.
  • popitem(): Removes and returns the last key-value pair in the dictionary.
  • clear(): Removes all key-value pairs in the dictionary.

Example:

# Using del to remove a key-value pair
del person["email"]  # Removes the "email" key and its value

# Using pop() to remove and get a value
removed_age = person.pop("age")  # Removes "age" and returns 26
print(removed_age)  # Output: 26

# Using popitem() to remove the last inserted key-value pair
last_item = person.popitem()  # Removes the last key-value pair
print(last_item)  # Output: ('city', 'New York')

# Using clear() to remove all items
person.clear()
print(person)  # Output: {}

Dictionary Methods

Python dictionaries come with several built-in methods for performing operations on key-value pairs.

Common methods:

  1. keys(): Returns a view of all keys in the dictionary.
    keys = person.keys()
    print(keys)  # Output: dict_keys(['name', 'age', 'city'])
    
  2. values(): Returns a view of all values in the dictionary.
    values = person.values()
    print(values)  # Output: dict_values(['Alice', 25, 'New York'])
    
  3. items(): Returns a view of all key-value pairs as tuples.
    items = person.items()
    print(items)  # Output: dict_items([('name', 'Alice'), ('age', 25), ('city', 'New York')])
    
  4. get(): Retrieves the value associated with a key. If the key does not exist, it returns None or a default value if specified.
    print(person.get("name"))  # Output: Alice
    print(person.get("email", "Not Available"))  # Output: Not Available
    
  5. update(): Adds multiple key-value pairs from another dictionary or iterable.
    person.update({"gender": "Female", "job": "Engineer"})
    print(person)
    # Output: {'name': 'Alice', 'age': 25, 'city': 'New York', 'gender': 'Female', 'job': 'Engineer'}
    

Nesting Dictionaries

Dictionaries can store other dictionaries as values, creating a nested structure. This is useful for representing hierarchical data.

Example of a nested dictionary:

people = {
    "person1": {"name": "Alice", "age": 25},
    "person2": {"name": "Bob", "age": 30}
}

# Accessing data from nested dictionary
print(people["person1"]["name"])  # Output: Alice

Iterating Over Dictionaries

You can iterate over dictionaries in several ways, such as by keys, values, or both.

Example of iterating over keys:

for key in person:
    print(key)  # Prints each key

Example of iterating over values:

for value in person.values():
    print(value)  # Prints each value

Example of iterating over key-value pairs:

for key, value in person.items():
    print(f"{key}: {value}")  # Prints key-value pair

Dictionary Comprehension

Dictionary comprehension provides a concise way to create a dictionary. It is similar to list comprehension but involves key-value pairs.

Example of dictionary comprehension:

# Creating a dictionary of squares
squares = {x: x**2 for x in range(5)}
print(squares)  # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Use Cases for Dictionaries

Dictionaries are essential for storing and managing data in many real-world scenarios:

  • Mapping data: Dictionaries are great for mapping unique identifiers to data, such as a mapping between student IDs and their grades.
  • Counting occurrences: Dictionaries can be used to count how often something appears, such as word frequency analysis.
  • Configuration settings: Storing configuration parameters with unique keys allows easy access and modification of settings.

Summary of Key-Value Pairs and Dictionary Operations

  • Key-value pairs form the foundation of dictionaries, where each unique key is associated with a corresponding value.
  • Dictionaries support operations like accessing, modifying, adding, and removing key-value pairs.
  • Common dictionary methods include keys(), values(), items(), get(), and update().
  • Python dictionaries are mutable and unordered, but provide efficient and flexible storage for data. They can be nested and used for complex data structures.

Dictionaries are versatile and efficient for managing and processing data in Python programs.

Commenting is not enabled on this course.