Dictionaries are fundamental data structures in Python. Here are key advanced operations to master:
1. Dictionary Methods
get(key, default)
- Safely retrieve valuesupdate(another_dict)
- Merge dictionariespop(key, default)
- Remove and return a valuesetdefault(key, default)
- Insert if key doesn't existitems()
- Return key-value pairs as tupleskeys()
,values()
- Extract keys or values
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
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?