Advertisement
❮ Previous: Python Sets & Set Operations Next: Python Arrays ❯

Python Dictionaries & Dictionary Comprehensions

Python dictionaries are one of the most versatile and heavily used built-in data structures. They store data in key-value pairs, allowing for ultra-fast lookups, insertions, and deletions.


1. Core Characteristics of Dictionaries


Advertisement

2. Creating and Accessing Dictionaries

# Creating a dictionary
student = {
    "name": "Alice",
    "age": 22,
    "major": "Computer Science",
    "courses": ["Data Structures", "Algorithms"]
}

# Accessing values
print(student["name"])          # Output: Alice
print(student.get("major"))     # Output: Computer Science

# Safe access with .get() (returns None or default instead of KeyError)
gpa = student.get("gpa", 3.8)   # Output: 3.8 (since 'gpa' doesn't exist yet)

Try this code ❯


Advertisement

3. Modifying Dictionaries

Operation Syntax Example Description
Add / Update student["age"] = 23 Adds key if missing; updates value if it exists.
Bulk Update student.update({"gpa": 3.9, "graduated": False}) Merges another dictionary or iterable of key-value pairs.
Remove (pop) removed_val = student.pop("major") Removes key and returns its value.
Remove (popitem) last_item = student.popitem() Removes and returns the last inserted (key, value) pair.
Clear student.clear() Removes all items from the dictionary.

Advertisement

4. Essential Dictionary Methods

scores = {"math": 90, "english": 85, "science": 92}

# Get all keys, values, or items
print(scores.keys())    # dict_keys(['math', 'english', 'science'])
print(scores.values())  # dict_values([90, 85, 92])
print(scores.items())   # dict_items([('math', 90), ('english', 85), ('science', 92)])

# Iterating over a dictionary
for subject, score in scores.items():
    print(f"{subject}: {score}")

Try this code ❯


Advertisement

5. Dictionary Comprehensions

Dictionary comprehensions provide a concise, readable way to construct dictionaries from any iterable, similar to list comprehensions.

Basic Syntax

{key_expression: value_expression for item in iterable if condition}

Examples

1. Transforming an existing dictionary (Squaring numbers):

numbers = [1, 2, 3, 4, 5]
squared_dict = {num: num**2 for num in numbers}
print(squared_dict)  # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Try this code ❯

2. Swapping keys and values:

original = {"a": 1, "b": 2, "c": 3}
swapped = {v: k for k, v in original.items()}
print(swapped)  # Output: {1: 'a', 2: 'b', 3: 'c'}

Try this code ❯

3. Filtering with a condition (Conditionally filtering a dictionary):

prices_usd = {"apple": 1.2, "banana": 0.5, "laptop": 999.0, "pen": 1.5}
# Keep only items under $5.00
affordable = {item: price for item, price in prices_usd.items() if price < 5.0}
print(affordable)  # Output: {'apple': 1.2, 'banana': 0.5, 'pen': 1.5}

Try this code ❯

❮ Previous: Python Sets & Set Operations Next: Python Arrays ❯
Advertisement