Dictionaries are fundamental data structures in Python. Here are key advanced operations to master:

1. Dictionary Methods

  • get(key, default) - Safely retrieve values
  • update(another_dict) - Merge dictionaries
  • pop(key, default) - Remove and return a value
  • setdefault(key, default) - Insert if key doesn't exist
  • items() - Return key-value pairs as tuples
  • keys(), values() - Extract keys or values
Python_Dictionary

2. Nested Dictionaries

students = {
    "Alice": {"age": 25, "grade": "A"},
    "Bob": {"age": 30, "grade": "B"}
}
print(students["Alice"]["grade"])  # Output: A

3. Dictionary Comprehensions

squares = {x: x**2 for x in range(1, 6)}
# Result: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

4. Merging Dictionaries

dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
merged = {**dict1, **dict2}  # Result: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

5. Real-World Example

Advanced_Operations

Use dictionaries to track inventory:

inventory = {
    "laptop": {"price": 1200, "stock": 50},
    "tablet": {"price": 600, "stock": 30}
}

For more basics, see Python Data Types.
Want to learn about dictionary performance optimization?