Skip to main content

Dictionaries (Part 2): Dictionary methods and dictionary comprehensions

In the previous article, we learned how to create dictionaries and access their values. Now, we'll explore how to modify, manage, and iterate over them using dictionary methods. We'll also introduce a powerful, Pythonic feature for creating dictionaries: dictionary comprehensions.


📚 Prerequisites

Before we begin, please ensure you have a solid grasp of the following concepts:

  • How to create a Python dictionary and access its values using keys.
  • Basic understanding of Python loops.

🎯 Article Outline: What You'll Master

In this article, you will learn:

  • Modifying Dictionaries: How to add, update, and remove key-value pairs.
  • Iterating Over Dictionaries: How to efficiently loop over keys, values, and items using .keys(), .values(), and .items().
  • Dictionary Comprehensions: A concise and readable way to create new dictionaries.
  • Practical Application: Building a word frequency counter to analyze text.

🧠 Section 1: Modifying Dictionaries

Since dictionaries are mutable, you can change them after they've been created.

1.1 - Adding and Updating Key-Value Pairs

You can add a new pair or update an existing one using simple square bracket assignment.

# CodeBlock1.py
# Adding and updating dictionary items

student = {
"name": "Alice",
"age": 21
}
print(f"Original student dict: {student}")

# Update an existing value
student["age"] = 22
print(f"After updating age: {student}")

# Add a new key-value pair
student["major"] = "Physics"
print(f"After adding major: {student}")

# Use the update() method to merge another dictionary
student.update({"gpa": 3.8, "is_active": True})
print(f"After update(): {student}")

Step-by-Step Code Breakdown:

  1. student["age"] = 22: Since the key "age" already exists, this assignment updates its value.
  2. student["major"] = "Physics": Since the key "major" does not exist, this assignment adds it to the dictionary.
  3. student.update({...}): The .update() method is perfect for adding multiple key-value pairs at once from another dictionary.

1.2 - Removing Key-Value Pairs

There are a few ways to remove items from a dictionary.

# CodeBlock2.py
# Removing dictionary items

student = {'name': 'Bob', 'age': 25, 'major': 'History', 'id': 123}
print(f"Original dict: {student}")

# Remove 'age' using pop()
age = student.pop("age")
print(f"Popped value: {age}")
print(f"After pop('age'): {student}")

# Remove the last inserted item using popitem()
last_item = student.popitem()
print(f"Popped item: {last_item}")
print(f"After popitem(): {student}")

# Remove 'name' using the del keyword
del student["name"]
print(f"After del student['name']: {student}")

Walkthrough:

  • .pop("age"): Removes the key "age" and returns its value. This is useful if you need to use the removed value.
  • .popitem(): Removes and returns the last key-value pair that was inserted (in modern Python). This is useful for processing items one by one.
  • del student["name"]: The del keyword removes a key-value pair. It does not return the value.

💻 Section 2: Iterating Over Dictionaries

Looping over dictionaries is a common task. The .items() method is the most powerful way to do it.

# IterationExample.py
# Looping over a dictionary

user_profile = {
"username": "py_dev",
"email": "[email protected]",
"followers": 1500
}

# Looping over keys (the default)
print("\n--- Looping over keys ---")
for key in user_profile:
print(key)

# Looping over values using .values()
print("\n--- Looping over values ---")
for value in user_profile.values():
print(value)

# Looping over key-value pairs using .items()
print("\n--- Looping over items (key-value pairs) ---")
for key, value in user_profile.items():
print(f"Key: {key}, Value: {value}")

Key Point: Using .items() is generally the most useful approach because it gives you both the key and the value in each iteration, which you can unpack into two variables (e.g., key, value).


🚀 Section 3: Dictionary Comprehensions

Like list comprehensions, dictionary comprehensions provide a short and elegant syntax for creating dictionaries.

The Syntax: {key_expression: value_expression for item in iterable}

# DictComprehension.py
# Demonstrating dictionary comprehensions

# Create a dictionary of numbers and their squares
squares = {x: x**2 for x in range(5)}
print(f"Squares dict: {squares}")

# Create a dictionary from an existing list
fruits = ["apple", "banana", "cherry"]
fruit_lengths = {fruit: len(fruit) for fruit in fruits}
print(f"Fruit lengths dict: {fruit_lengths}")

# Create a dictionary with a condition
original_prices = {"apple": 1.0, "banana": 0.5, "cherry": 2.0}
sale_prices = {item: price * 0.8 for (item, price) in original_prices.items() if price > 0.75}
print(f"Sale prices dict: {sale_prices}")

Walkthrough:

  1. {x: x**2 for x in range(5)}: Creates a dictionary where keys are numbers from 0-4 and values are their squares.
  2. {fruit: len(fruit) for fruit in fruits}: Creates a dictionary where keys are fruit names and values are their lengths.
  3. {... for (item, price) in original_prices.items() if price > 0.75}: This is a more advanced example. It iterates over the items of the original_prices dictionary and creates a new dictionary containing only the items where the price is greater than 0.75, applying a 20% discount to them.

🛠️ Section 4: Project-Based Example: Word Frequency Counter

Let's use what we've learned to count the frequency of words in a sentence.

# ProjectExample.py
# The full Python code for the mini-project.

sentence = "the quick brown fox jumps over the lazy dog"
words = sentence.split()
word_counts = {}

# Use a for loop to count words
for word in words:
# Use .get() to handle the first time we see a word
word_counts[word] = word_counts.get(word, 0) + 1

print(f"All word counts: {word_counts}")

# Now, use a dictionary comprehension to find words that appear more than once
repeated_words = {word: count for (word, count) in word_counts.items() if count > 1}
print(f"Repeated words: {repeated_words}")

Walkthrough:

  1. We split the sentence into a list of words.
  2. We loop through the words list. For each word:
    • word_counts.get(word, 0) safely gets the current count of the word. If the word isn't in the dictionary yet, it returns the default value 0.
    • We add 1 to this count and assign it back to word_counts[word].
  3. Finally, we use a dictionary comprehension to filter our word_counts dictionary, creating a new one that only includes the words with a count greater than 1.

💡 Conclusion & Key Takeaways

You now have a comprehensive toolkit for working with Python dictionaries. You can create, access, modify, and iterate over them with ease and efficiency.

Let's summarize the key Python takeaways:

  • Use dict[key] = value to add or update items.
  • Use .pop(key) or del dict[key] to remove items.
  • Loop over dictionaries using .keys(), .values(), or, most commonly, .items() for key-value pairs.
  • Use dictionary comprehensions ({k:v for ...}) for a concise way to create new dictionaries.

Challenge Yourself (Python Edition): Take the word_counts dictionary from the project and use a dictionary comprehension to create a new dictionary where the keys are the words and the values are the words written backward.


➡️ Next Steps

We've covered lists, tuples, and dictionaries. In the next article, "Sets: Unordered collections of unique items. Set operations.", we'll explore the final core collection type in Python, which is all about uniqueness.

Keep practicing, keep exploring, and enjoy your Python coding adventure!


Glossary (Python Terms)

  • Dictionary Method: A function that is associated with a dictionary object (e.g., .pop(), .items()).
  • Dictionary Comprehension: A concise syntax for creating dictionaries from iterables.
  • View Object: What .keys(), .values(), and .items() return. It's a dynamic view of the dictionary's entries, which means that when the dictionary changes, the view reflects these changes.

Further Reading (Python Resources)