Python Dictionary

Unlock the power and flexibility of Python dictionary! Store data in key-value pairs for lightning-fast lookups, effortless updates, and clear organization. This fundamental data structure is ideal for situations where you need to associate unique keys with their corresponding values. Python dictionaries can streamline your workflow and enhance your code’s efficiency, whether building applications, working with data analysis, or tackling machine learning tasks.

Python-Dictionary
Table of Contents

What is a Python dictionary?

Python dictionary is a special type of collection that stores information like a phonebook. Unlike ordered lists, dictionaries organize data using key-value pairs. Imagine each key as a unique nickname for a value you want to store.

Python Dictionary Syntax

dictionary_name = {“key1”: value1, “key2”: value2, …}

  • dictionary_name: Name you choose for your dictionary.
  • key1, key2, etc.: Unique labels (like nicknames) for the data you store. Keys must be immutable, meaning they can’t be changed after creation (e.g., strings or numbers).
  • value1, value2, etc.: The data you want to associate with each key. Values can be any data type in Python (numbers, strings, lists, even other dictionaries!)

Python Dictionary Example

phonebook = {"Alice": "123-456-7890", "Bob": "987-654-3210"}
print(phonebook["Alice"])  # Output: 123-456-7890 (Access value using key)

Explanation

  • Line 1: Creates a dictionary named phonebook. “Alice” and “Bob” are the keys, and their corresponding phone numbers are the values.
  • Line 2: Prints the phone number associated with the key “Alice”. This demonstrates how to access a value using its key within the dictionary.

Exploring Dictionary Keys

In Python dictionaries, keys act like unique identification tags for the data you store. They’re essential for retrieving specific values. Unlike list indexes (which are numerical and sequential), dictionary keys can be various data types as long as they’re immutable (unchangeable).

Syntax: Accessing Values by Key

value = dictionary_name[“key”]

  • key: The unique label you used to store the value you want to access.

Example: Accessing Values Using Keys

colors = {"red": "#FF0000", "green": "#00FF00", "blue": "#0000FF"}

red_hex = colors["red"]  # Access the value for key "red"
print(red_hex)  # Output: #FF0000

# Trying to access a non-existent key will result in a KeyError
unknown_color = colors["purple"]  # This line will cause an error (key "purple" doesn't exist)

Explanation

  • Lines 1-4: Create a dictionary colors where color names are keys and their hexadecimal codes are values. We then retrieve the value (hex code) associated with the key “red” and print it.
  • Line 7: This line is included to demonstrate that attempting to access a non-existent key will result in a KeyError.

Understanding Dictionary Values

In Python dictionary, the real stars of the show are the values. You want to store and retrieve these pieces of data using unique keys. Values can be any data type in Python, giving you immense flexibility. You can store numbers, strings, lists, or dictionaries in a dictionary!

Syntax: Adding Key-Value Pairs

dictionary_name[“key”] = value

  • key: You’ll use the unique label (like a nickname) to access this value later.
  • value: The data you want to store under that specific key.

Example: Adding Key-Value Pairs to a Dictionary

student_info = {}  # Create an empty dictionary

student_info["name"] = "Alice"  # Add a key-value pair for student's name
student_info["age"] = 12  # Add a key-value pair for student's age
student_info["courses"] = ["Math", "Science", "English"]  # Add a list as a value

print(student_info)  # Output: {'name': 'Alice', 'age': 12, 'courses': ['Math', 'Science', 'English']}

Explanation

  • Lines 1-5: Create an empty dictionary student_info and add several key-value pairs. Notice how we can add data types (string, integer, and list) as values.
  • Line 7: Prints the entire dictionary, showcasing the key-value pairs we created.

Key Uniqueness Requirement

Unlike many other collections in Python, dictionaries enforce strict rules about keys. A Python dictionary can only have unique keys. This makes sense because keys act as identifiers for retrieving specific values. If you tried to have duplicate keys, how would you know which value to return?

Key Uniqueness in Dictionaries

  • A dictionary cannot have two key-value pairs with the same key.
  • Attempting to add a duplicate key will overwrite the previous value associated with that key.

Example

toppings = {"cheese": "mozzarella", "sauce": "tomato"}

toppings["cheese"] = "cheddar"  # Update the value for the existing key "cheese"

print(toppings)  # Output: {'cheese': 'cheddar', 'sauce': 'tomato'}

Explanation

  • Lines 1-3: Create a dictionary toppings with cheese and sauce types. Then, we update the value for the key “cheese” from “mozzarella” to “cheddar”.
  • Line 5: Prints the updated dictionary, demonstrating how the original value for “cheese” was overwritten.

Note: Although you can’t have duplicate keys, you can have duplicate values in a dictionary. Multiple keys can point to the same value if that value is relevant for different entries.


Methods for Creating Python Dictionaries

There are two main ways to create dictionaries in Python, which offer flexibility for different situations:

Constructing Dictionaries with Curly Braces { }

Curly braces in Python offer a direct and intuitive way to create dictionaries. Think of the opening curly brace ({) as marking the beginning of your dictionary and the closing one (}) as the end. Inside, you define key-value pairs separated by colons (:). Each key is like a unique label; the value is the information you store under that label. Curly braces make it easy to see the structure of your dictionary at a glance.

Syntax

dictionary_name = {“key1”: value1, “key2”: value2, …}

Example

car_info = {"brand": "Ford", "model": "Mustang", "year": "1967"}  # Create a dictionary

Creates a dictionary named car_info containing information about a car.

Utilizing the dict() Constructor

The dict() function in Python acts as a constructor, specifically for creating dictionaries. It takes key-value pairs as input and builds a dictionary for you.

Syntax

dictionary_name = dict(key1=value1, key2=value2, …)

Example

fruits = dict(apple="red", banana="yellow", orange="orange")
print(fruits)  # Output: {'apple': 'red', 'banana': 'yellow', 'orange': 'orange'}

Explanation

  • Line 1: Creates a dictionary named fruits using dict(). We provide key-value pairs for different fruits and their colors.
  • Line 2: Prints the entire dictionary, showing the keys and their corresponding values.

Adding Elements to Python Dictionaries

Python dictionaries are dynamic, meaning you can add new items (key-value pairs) even after creating the dictionary. This is useful when you’re collecting information or building the dictionary step-by-step. There are two main ways to add items:

Direct Assignment: Assign a value to a new key within the dictionary structure.

Syntax

dictionary_name[“key”] = value

Example

capitals = {"France": "Paris", "Italy": "Rome"}

capitals["Germany"] = "Berlin"  # Add a new key-value pair for Germany

print(capitals)  # Output: {'France': 'Paris', 'Italy': 'Rome', 'Germany': 'Berlin'}

Explanation

  • Lines 1-3: Create a dictionary capitals with two countries and their capitals. Then, we add a new key-value pair for Germany using the assignment operator (=) on the existing dictionary.
  • Line 5: Prints the updated dictionary, demonstrating the new entry for Germany.

Modifying Items in Python Dictionaries

Python dictionary is designed to be modifiable, allowing you to update the values associated with existing keys. Here are common ways to achieve this:

Updating Values with Direct Assignment

Direct assignment provides a straightforward way to update values in Python dictionaries. To modify the value associated with an existing key, reference the dictionary and its key, then assign a new value using the equals sign (=). If the key doesn’t exist, this method will create a new key-value pair.

Syntax

dictionary_name[“key”] = new_value

Overwrites the value associated with an existing key.

Employing the update() Method

The update() method efficiently updates a Python dictionary with multiple key-value pairs simultaneously. You can use update() to merge key-value pairs from another dictionary or an iterable of key-value pairs, like a list of tuples. Inside the update() function, provide the new key-value pairs within curly braces, separated by commas.

Syntax

dictionary_name.update({“key1”: new_value1, “key2”: new_value2, …})

update(): The method merges in key-value pairs from another dictionary or iterable.

Example

car = {"brand": "Ford", "model": "Mustang", "year": 1967} 

# Direct Assignment
car["color"] = "red"  # Add a new key-value pair
car["year"] = 1969  # Update the existing "year" value

# Using update()
car.update({"mileage": 85000}) 

print(car)  # Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1969, 'color': 'red', 'mileage': 85000}

Explanation

  • Lines 1-5: Create a dictionary car and demonstrate updating an existing value and adding a new key-value pair using direct assignment.
  • Lines 8: Use update() to merge in new key-value pairs.
  • Line 10: Print the updated car dictionary.

Accessing Items within Python Dictionaries

Accessing items in a Python dictionary is centered around using their unique keys. Let’s explore how to retrieve values:

Accessing Values by Key

Retrieving values from a Python dictionary directly involves their associated keys. Think of the key as the address of the data you want. To access a specific value, reference the dictionary name followed by the key within square brackets ([ ]).

Syntax

value = dictionary_name[“key”]

The get() Method for Safe Access

Python’s .get() method offers a safer alternative to directly accessing dictionary values by key. The key advantage of .get() is how it handles missing keys. Instead of throwing a KeyError if the key you’re looking for doesn’t exist, .get() returns None. This helps prevent your code from crashing unexpectedly. 

Syntax

value = dictionary_name.get(“key”)

Provides a safer way to access values. If the key doesn’t exist, it returns None instead of raising a KeyError.

Example

student = {"name": "Alice", "age": 20, "major": "Computer Science"} 

name = student["name"]  # Accessing the student's name 

grade = student.get("grade")  # grade key doesn't exist, returns None

print(name)  # Output: Alice
print(grade)  # Output: None

Explanation

  • Lines 1: Create a student dictionary.
  • Line 3: Demonstrates direct access by key.
  • Line 5: Uses .get() to safely handle a potentially missing key.
  • Lines 7-8: Print the retrieved value (name) and the result of .get() when a key doesn’t exist (None).

Deleting Elements from Python Dictionaries

Removing items from a Python dictionary is essential to keep your data organized. You have several methods at your disposal. The del statement directly deletes a key-value pair based on its key. The pop() method removes a key-value pair and returns the associated value. The popitem() method removes an arbitrary key-value pair. If you must remove all items immediately, empty the dictionary using the clear() method.

Removing with the del Keyword

The del keyword provides a concise way to remove key-value pairs from your Python dictionaries. Think of it as erasing an item using its key.

Syntax

del dictionary_name[“key”]

Example

clothes = {"shirt": "blue", "pants": "black", "hat": "red"}

del clothes["hat"]  # Remove the key-value pair with key "hat"

print(clothes)  # Output: {'shirt': 'blue', 'pants': 'black'}

Explanation

  • Lines 1-3: Create a dictionary clothes and then use del to remove the key-value pair for “hat”.
  • Line 5: Prints the updated dictionary, showing “hat” is gone.

Targeted Removal with pop()

The pop() method in Python dictionaries offers a way to remove items and get their values in one step. It’s like removing an item from a list and capturing it simultaneously.

Syntax

value = dictionary_name.pop(“key”)

value: Stores the value that was associated with the removed key.

Example

fruits = {"apple": "red", "banana": "yellow", "orange": "orange"}

removed_fruit = fruits.pop("banana")  # Remove "banana" and store its value

print(fruits)  # Output: {'apple': 'red', 'orange': 'orange'}
print(removed_fruit)  # Output: yellow (the value associated with "banana")

Explanation

  • Lines 1-3: Create a dictionary fruits. Then, we use pop("banana") to remove the key-value pair for “banana” and store the value (“yellow”) in the variable removed_fruit.
  • Lines 5-6: Print the modified dictionary (without “banana”) and the captured value (“yellow”).

Removing Arbitrary Key-Value Pairs Using popitem()

The popitem() method in Python dictionaries is useful when removing an arbitrary key-value pair, but you don’t care about a specific key. It’s like picking an item out of a bag without looking.

Syntax

key, value = dictionary_name.popitem()

Example

colors = {"red": "#FF0000", "green": "#00FF00", "blue": "#0000FF"}

removed_color = colors.popitem()  # Remove and store an arbitrary key-value pair

print(colors)  # Output: {'red': '#FF0000', 'green': '#00FF00'} (may vary based on which item was removed)
print(removed_color)  # Output: ('blue', '#0000FF') (key-value pair as a tuple)

Explanation

  • Line 1: Create a dictionary colors.
  • Line 3: Use popitem() to remove and store an arbitrary key-value pair in the tuple removed_color.
  • Lines 5-6: Print the modified dictionary (one key-value pair is removed) and the popped item as a tuple (key, value). The key-value pair removed may vary depending on the dictionary’s internal order.

Clearing a Dictionary with clear()

The clear() method in Python dictionaries lets you wipe the slate clean in one fell swoop. It’s like emptying a bucket all at once.

Syntax

dictionary_name.clear()

Example

toppings = {"cheese": "mozzarella", "sauce": "tomato", "pepperoni": "sliced"}

toppings.clear()  # Remove all key-value pairs from the dictionary

print(toppings)  # Output: {}

Explanation

  • Lines 1-3: Create a dictionary toppings and then use clear() to remove all its key-value pairs.
  • Line 5: Prints the dictionary after clearing it, showing it’s now empty ({}).

Determining Dictionary Size with len()

Determining the number of items (key-value pairs) in a Python dictionary is straightforward. You can use the built-in len() function, which is similar to finding the length of lists or strings.

Syntax

number_of_items = len(dictionary_name)

len(): This function calculates the length of various objects in Python.

Example

customer = {"name": "Alice", "age": 30, "city": "New York"}

num_items = len(customer)  # Get the number of key-value pairs

print(num_items)  # Output: 3

Explanation

  • Lines 1-3: Create a dictionary customer and use len() to find the number of items in it.
  • Line 5: Prints the length of the dictionary, which is 3 (number of key-value pairs).

Key Membership Tests: in and not in

The in and not in operators are handy tools in Python to check for membership in dictionaries. They primarily look for keys, not values.

Syntax

key in dictionary_name
key not in dictionary_name

Explanation

  • Lines 1: Checks if the key exists in the dictionary.
  • Lines 2: Checks if the key does not exist in the dictionary.

Example

fruits = {"apple": "red", "banana": "yellow", "orange": "orange"}

is_apple_in_basket = "apple" in fruits  # Check if "apple" is a key

print(is_apple_in_basket)  # Output: True

is_mango_in_basket = "mango" not in fruits  # Check if "mango" is not a key

print(is_mango_in_basket)  # Output: True

Explanation

  • Lines 1-2: Create a dictionary fruits and use the in operator to see if “apple” exists as a key.
  • Lines 3-4: Print the results. The first check returns True because “apple” is a key, and the second check returns True because “mango” is not a key in the dictionary.

Extracting a List of Keys with keys()

The keys() method is a handy tool in Python dictionaries. It allows you to retrieve a view of all the unique keys within the dictionary. This view acts like a list but is more memory-efficient for large dictionaries.

Syntax

all_keys = my_dictionary.keys()

  • my_dictionary: The dictionary from which you want to extract keys.
  • .keys(): The keys() method is called on the dictionary object.
  • all_keys: The result is an iterable object (often a view) containing all the unique keys in the dictionary.

Example

products = {"SKU": "ABC123", "name": "T-Shirt", "color": "blue"}
for key in products.keys():  # Loop through all keys
    print(key)  # Output: SKU, name, color

Explanation

  • Line 1: Creates a dictionary products with some product information.
  • Line 2: Uses products.keys() to get an iterable containing all the keys from the dictionary. The for loop iterates through each key.
  • Line 3: Prints each key in the dictionary, demonstrating how to access them using the keys() method.

Retrieving a List of Values with values()

The values() method is another useful function associated with dictionaries. It provides a way to access all the associated values within a dictionary, regardless of their corresponding keys. This is helpful when you need to process or iterate through just the data values themselves.

Syntax

all_values = my_dictionary.values()

  • my_dictionary: The dictionary from which you want to extract values.
  • .values(): The values() method is called on the dictionary object.
  • all_values: The result is an iterable object (often a view) containing all the values in the dictionary but not the keys.

Example

inventory = {"apple": 10, "banana": 15, "orange": 8}
for value in inventory.values():  # Loop through all values
    print(f"Quantity: {value}")  # Output: Quantity: 10, Quantity: 15, Quantity: 8

Explanation

  • Line 1: Creates a dictionary inventory with fruits as keys and their quantities as values.
  • Line 2: Uses inventory.values() to get an iterable containing all the values (quantities) from the dictionary. The for loop iterates through each value.
  • Line 3: Prints a message with a label displaying each value (quantity). This demonstrates how to access values using the values() method.

Obtaining Key-Value Tuples with items()

The items() method is a built-in function associated with dictionaries in Python. It provides a convenient way to access the keys and their associated values simultaneously. This is useful when processing or iterating through all the key-value pairs within a dictionary.

Syntax

key_value_pairs = my_dictionary.items()

  • my_dictionary: The dictionary from which you want to extract key-value pairs.
  • .items(): The items() method is called on the dictionary object.
  • key_value_pairs: The result is an iterable object (often a view) containing tuples. Each tuple represents a key-value pair, with the key in the first element and the value in the second element.

Example

customer = {"name": "Alice", "age": 30, "city": "New York"}
for key, value in customer.items():  # Loop through key-value pairs
    print(f"{key}: {value}")  # Output: name: Alice, age: 30, city: New York

Explanation

  • Line 1: Creates a dictionary customer with key-value pairs representing customer information.
  • Line 2: Uses customer.items() to get an iterable containing key-value pairs as tuples. The for loop unpacks each tuple into key and value variables.
  • Line 3: Prints the key and corresponding value in a formatted string. This demonstrates iterating through the key-value pairs.

Copying Python Dictionaries with copy()

When you need a new dictionary that reflects the current state of your original dictionary but independent of future changes, the copy() method comes in handy. It creates a shallow copy, meaning any changes you make to the copy won’t affect the original, and vice versa.

Syntax

copied_dictionary = my_dictionary.copy()

  • my_dictionary: The dictionary you want to copy.
  • .copy(): The copy() method is called on the dictionary object.
  • copied_dictionary: The result is a new dictionary that is a shallow original copy.

Example

original_dict = {"name": "Alice", "age": 30}
copied_dict = original_dict.copy()  # Create a shallow copy
original_dict["age"] = 35  # Modify the original dictionary
print(original_dict["age"])  # Output: 35 (original is modified)
print(copied_dict["age"])  # Output: 30 (copy remains unchanged)

Explanation

  • Line 1: Creates a dictionary original_dict with some key-value pairs.
  • Line 2: Uses original_dict.copy() to create a shallow copy named copied_dict.
  • Line 3: Modifies the value associated with the key “age” in the original_dict.
  • Line 4: Prints the value for “age” from the original_dict, demonstrating the change.
  • Line 5: Prints the value for “age” from the copied_dict. Since it’s a shallow copy, the modification in the original dictionary isn’t reflected here.

Iterating Through Python Dictionaries

Traversing key-value pairs in Python dictionaries is a breeze with the built-in keys(), values(), and items() methods. These methods provide different ways to iterate through the dictionary’s contents:

  • Looping through Keys: Use keys() to get an iterable of all unique keys. The for loop iterates through each key.
  • Looping through Values: Use values() to get an iterable of all the values in the dictionary. The for loop iterates through each value.
  • Looping through Key-Value Pairs: Use items() to get an iterable containing tuples of key-value pairs. The for loop unpacks each tuple into separate variables for the key and value.

Example (Using all three methods)

user_data = {"name": "Bob", "city": "New York", "age": 40}
# Looping through keys
for key in user_data.keys():
    print(f"Key: {key}")  # Output: Key: name, Key: city, Key: age
# Looping through values
for value in user_data.values():
    print(f"Value: {value}")  # Output: Value: Bob, Value: New York, Value: 40
# Looping through key-value pairs
for key, value in user_data.items():
    print(f"{key}: {value}")  # Output: name: Bob, city: New York, age: 40

Explanation

  • Line 1: Creates a dictionary user_data with some user information.
  • Line 3: Demonstrates looping through keys using keys().
  • Line 4: Prints each key inside the dictionary.
  • Line 6: Demonstrates looping through values using values().
  • Line 7: Prints each value (data) associated with the keys.
  • Line 9: Demonstrates looping through key-value pairs using items().
  • Line 10: Unpacks each tuple from items() into key and value variables. Prints both the key and its value.

Working with Nested Dictionaries in Python

Python dictionaries allow you to create hierarchical structures by nesting dictionaries within other dictionaries. This is useful for representing complex data that has categories and subcategories.

Syntax

nested_dict = {
    "category1": {
        "key1": value1,
        "key2": value2
    },
    "category2": {
        "key3": value3,
        "key4": value4
    }
}
  • nested_dict: The main dictionary that holds the nested structure.
  • category1, category2: These are keys for the top level of nesting, representing categories.
  • key1, key2, key3, key4: Keys for elements within the nested dictionaries.
  • value1, value2, value3, value4: The values associated with their respective keys.

Example

company_data = {
    "employees": {
        "Alice": {"department": "Marketing", "age": 30},
        "Bob": {"department": "Sales", "age": 35}
    }
}
# Accessing data within nested dictionaries
print(company_data["employees"]["Alice"]["department"])  # Output: Marketing

Explanation

  • Line 1: Creates a dictionary company_data.
  • Line 2: The first level key “employees” holds another dictionary with employee details.
  • Line 3-4: “Alice” and “Bob” are keys within the nested “employees” dictionary, each with their department and age information.
  • Line 7: Demonstrates accessing nested data using nested indexing.
  • Line 8: Prints the department of “Alice” by chaining dictionary lookups.

Accessing Elements in Nested Dictionaries

Nested dictionaries organize complex data. Similar to nested lists, you can access elements within these structures using nested indexing.

Syntax

nested_dict = { … }  # Refer to previous example for structure
element_value = nested_dict[“outer_key”][“inner_key”]

  • nested_dict: The main dictionary containing the nested structure.
  • outer_key: The key for the first level of nesting.
  • inner_key: The key for the element within the nested dictionary.
  • element_value: The value associated with the specified key in the nested structure.

Example

company_data = {
    "employees": {
        "Alice": {"department": "Marketing", "age": 30},
        "Bob": {"department": "Sales", "age": 35}
    }
}
# Accessing Alice's age
alice_age = company_data["employees"]["Alice"]["age"]
print(f"Alice's age: {alice_age}")  # Output: Alice's age: 30

Explanation

  • Line 1-6: Same as the previous example, creating a nested dictionary company_data with employee information.
  • Line 8: Uses nested indexing to retrieve the value associated with the key “age” within the nested dictionary for “Alice”.
  • Line 9: Prints a message displaying Alice’s age. This demonstrates how to access data within nested structures.

Modifying Values Within Nested Structures

Since dictionaries are mutable, you can modify elements within nested dictionaries, allowing you to update or change data within the structure.

Syntax

nested_dict = { … }  # Refer to previous example for structure
# Modify value for a key within a nested dictionary
nested_dict[“outer_key”][“inner_key”] = new_value

new_value: The new value you want to assign to the specified key.

Example

company_data = {
    "employees": {
        "Alice": {"department": "Marketing", "age": 30},
        "Bob": {"department": "Sales", "age": 35}
    }
}
# Update Alice's department
company_data["employees"]["Alice"]["department"] = "Engineering"
print(company_data["employees"]["Alice"]["department"])  # Output: Engineering

Explanation

  • Line 1-6: As in previous examples, creating a nested dictionary company_data with employee information.
  • Line 8: Uses nested indexing to target the key “department” within the nested dictionary for “Alice” and assigns a new value “Engineering”.
  • Line 9: Prints the department for “Alice” again, demonstrating the update. This shows how to modify elements within nested structures.

Adding Elements to Nested Dictionaries

Nested dictionaries offer flexibility when you need to add new information. You can create elements at different levels within the structure.

Syntax

nested_dict = { … }  # Refer to previous example for structure

# Add a new key-value pair to an existing nested dictionary
nested_dict[“outer_key”][“new_inner_key”] = new_value

# Add a new key-value pair to the top level
nested_dict[“new_outer_key”] = new_value

  • nested_dict: The main dictionary containing the nested structure.
  • outer_key: The key for the existing level where you want to add a new element.
  • new_inner_key: The key for the new element you add within the nested dictionary.
  • new_value: The value associated with the new key.
  • new_outer_key: The key for a new element at the top level of the nested dictionary.

Example

company_data = {
    "employees": {
        "Alice": {"department": "Marketing", "age": 30},
        "Bob": {"department": "Sales", "age": 35}
    }
}
# Add a new employee "Charlie"
company_data["employees"]["Charlie"] = {"department": "Finance", "age": 28}
# Add a new key "location" at the top level
company_data["location"] = "New York"
print(company_data)  # Output: Shows the updated dictionary with new elements

Explanation

  • Line 1-6: As in previous examples, creating a nested dictionary company_data with employee information.
  • Line 8: Adds a new key-value pair for “Charlie” within the “employees” dictionary.
  • Line 9-10: Adds a new key, “location” at the top level of the nested dictionary.
  • Line 11: Prints the entire dictionary, showcasing the addition of new elements at different levels.

Removing Elements from Nested Dictionaries

Nested dictionaries provide a way to organize complex data, but sometimes, you must remove elements. Python offers a couple of methods for this task.

Syntax (Using del)

nested_dict = { … }  # Refer to previous example for structure

# Remove an element using nested indexing and del
del nested_dict[“outer_key”][“inner_key”]

Syntax (Using pop)

nested_dict = { … }  # Refer to previous example for structure

# Remove an element using nested indexing and pop(optional argument)
removed_value = nested_dict[“outer_key”].pop(“inner_key”)

removed_value: The value associated with the removed element (optional with pop).

Example

company_data = {
    "employees": {
        "Alice": {"department": "Marketing", "age": 30},
        "Bob": {"department": "Sales", "age": 35},
        "Charlie": {"department": "Finance", "age": 28}
    }
}
# Remove Charlie using del
del company_data["employees"]["Charlie"]
# Remove Alice's department (keeping Alice) using pop
removed_department = company_data["employees"]["Alice"].pop("department")
print(company_data)  # Output: Shows the updated dictionary with Charlie removed and Alice's department gone

Explanation

  • Line 1-6: As in previous examples, creating a nested dictionary company_data with employee information.
  • Line 8: Uses nested indexing with del to remove the key-value pair for “Charlie” entirely.
  • Line 10: Uses nested indexing with pop("department") to remove only the “department” key from Alice’s information.
  • removed_department captures the value that was removed (department in this case). This is optional with pop.
  • Line 12: Prints the entire dictionary, showcasing the removal of “Charlie” and Alice’s department.

Iterating Through Nested Dictionaries

Nested dictionaries require special techniques when you need to iterate through all elements. Here’s a common approach that involves nested loops:

Syntax

nested_dict = { ... }  # Refer to previous example for structure

# Looping through all key-value pairs (outermost level first)
for outer_key, inner_dict in nested_dict.items():
    for inner_key, value in inner_dict.items():
        # Process each key-value pair from the inner dictionary
        print(f"{outer_key}-{inner_key}: {value}")

Example

company_data = {
    "employees": {
        "Alice": {"department": "Marketing", "age": 30},
        "Bob": {"department": "Sales", "age": 35}
    }
}
# Looping through all employees
for department, employee_info in company_data["employees"].items():
    print(f"Employee: {department}")
    for key, value in employee_info.items():
        print(f"  {key}: {value}")

Explanation

  • Line 1-6: As in previous examples, creating a nested dictionary company_data with employee information.
  • Line 8: The outer loop iterates through key-value pairs in the “employees” dictionary. department stores the department name (outer key), and employee_info stores the inner dictionary for that department.
  • Line 9: Prints the department name for each iteration.
  • Line 10-11: The inner loop iterates through key-value pairs within the employee_info dictionary (inner dictionary). key stores the key like “department” or “age”, and value stores the associated value.
  • Line 11: Prints each key-value pair with an indentation for the inner information of each employee.