Web Analytics

Dictionaries

Beginner ~25 min read

Dictionaries are Python's built-in mapping type - they store data as key-value pairs. Think of them like a real dictionary where you look up a word (key) to find its definition (value). They're incredibly fast for lookups and one of Python's most useful data structures!

Creating Dictionaries

Dictionaries are created with curly braces {} containing key: value pairs, or with the dict() constructor. Keys must be immutable (hashable), but values can be anything.

Output
Click Run to execute your code
Dictionary Properties: Since Python 3.7, dictionaries maintain insertion order. Keys must be unique and immutable (strings, numbers, tuples). Values can be any type including lists, other dictionaries, or even functions!

Accessing Dictionary Values

Access values using square brackets dict[key] or the safer get() method. Use in to check if a key exists, and keys(), values(), items() to get different views.

Output
Click Run to execute your code
Pro Tip: Always use get() when the key might not exist. dict.get('key', default) returns the default value instead of raising a KeyError. This makes your code more robust and avoids try/except blocks.

Modifying Dictionaries

Dictionaries are mutable - you can add, update, and remove key-value pairs. Use assignment, update(), pop(), and del to modify your dictionaries.

Output
Click Run to execute your code

Looping Through Dictionaries

Iterate over keys, values, or both using keys(), values(), and items(). The default iteration is over keys.

Output
Click Run to execute your code
Don't Modify While Iterating! Never add or remove keys while looping through a dictionary - it will raise a RuntimeError. Instead, iterate over a copy (dict.copy()) or build a new dictionary.

Common Mistakes

1. KeyError when accessing missing key

# Wrong - raises KeyError
person = {"name": "Alice"}
print(person["age"])  # KeyError: 'age'

# Correct - use get() with default
print(person.get("age", "Unknown"))  # "Unknown"

# Or check first
if "age" in person:
    print(person["age"])

2. Using mutable objects as keys

# Wrong - lists are mutable/unhashable
my_dict = {[1, 2]: "value"}  # TypeError!

# Correct - use tuples instead
my_dict = {(1, 2): "value"}  # Works!

3. Modifying dict while iterating

# Wrong - modifying size during iteration
for key in my_dict:
    if some_condition:
        del my_dict[key]  # RuntimeError!

# Correct - iterate over copy or use comprehension
for key in list(my_dict.keys()):  # Creates copy of keys
    if some_condition:
        del my_dict[key]

# Or build new dict
my_dict = {k: v for k, v in my_dict.items() if not some_condition}

4. Overwriting when you meant to update

# Wrong - completely replaces the dict
config = {"debug": True, "verbose": False}
config = {"timeout": 30}  # Lost debug and verbose!

# Correct - update existing dict
config.update({"timeout": 30})
# Or
config["timeout"] = 30

Exercise: Student Profile

Task: Create and modify a dictionary representing a student.

Requirements:

  • Create a dictionary with name, age, and grade
  • Update the grade to "A+"
  • Add a new key "subject" with value "Computer Science"
Output
Click Run to execute your code
Show Solution
# Create student dictionary
student = {
    "name": "John",
    "age": 20,
    "grade": "B"
}
print(f"Original: {student}")

# Update grade to A+
student["grade"] = "A+"
print(f"After grade update: {student}")

# Add subject
student["subject"] = "Computer Science"
print(f"Final: {student}")

Summary

  • Creating: {"key": value} or dict(key=value)
  • Accessing: dict[key] or dict.get(key, default)
  • Adding/Updating: dict[key] = value or dict.update()
  • Removing: del dict[key], dict.pop(key), dict.clear()
  • Checking: key in dict
  • Looping: .keys(), .values(), .items()
  • Properties: Ordered (3.7+), mutable, unique keys, O(1) lookup

What's Next?

Now let's learn Dictionary Comprehensions - the elegant, one-liner way to create and transform dictionaries, similar to list comprehensions!