Dictionary Manipulation
Basic Modification Operations
Adding and Updating Elements
## Creating a base dictionary
user_data = {"name": "LabEx User", "age": 25}
## Adding a new key-value pair
user_data["email"] = "[email protected]"
## Updating an existing value
user_data["age"] = 26
## Using update() method for multiple updates
user_data.update({"city": "San Francisco", "active": True})
Removing Elements
## Removing a specific key-value pair
del user_data["city"]
## Remove and return value using pop()
email = user_data.pop("email")
## Remove last inserted item
last_item = user_data.popitem()
Advanced Manipulation Techniques
Dictionary Copying
## Shallow copy
original_dict = {"a": 1, "b": 2}
shallow_copy = original_dict.copy()
## Deep copy (for nested dictionaries)
import copy
deep_copy = copy.deepcopy(original_dict)
Merging Dictionaries
## Python 3.9+ merge operator
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
merged_dict = dict1 | dict2
## Traditional update method
dict1.update(dict2)
Key and Value Extraction
## Dictionary methods
sample_dict = {"name": "John", "age": 30, "city": "New York"}
## Get all keys
keys = list(sample_dict.keys())
## Get all values
values = list(sample_dict.values())
## Get key-value pairs as tuples
items = list(sample_dict.items())
## Dictionary comprehension for filtering
original = {"a": 1, "b": 2, "c": 3, "d": 4}
filtered_dict = {k: v for k, v in original.items() if v % 2 == 0}
## Transforming dictionary values
transformed = {k: v * 2 for k, v in original.items()}
Dictionary Operations Complexity
Operation |
Time Complexity |
Description |
Accessing |
O(1) |
Constant time |
Insertion |
O(1) |
Constant time |
Deletion |
O(1) |
Constant time |
Searching |
O(n) |
Linear time |
Error Handling
## Safe dictionary access
user_profile = {"name": "LabEx User"}
## Using get() with default value
age = user_profile.get("age", "Not specified")
## Handling KeyError
try:
value = user_profile["non_existent_key"]
except KeyError:
print("Key does not exist")
Practical Workflow
graph TD
A[Original Dictionary] --> B{Manipulation}
B --> C[Adding Elements]
B --> D[Removing Elements]
B --> E[Updating Values]
B --> F[Filtering]
F --> G[Transformed Dictionary]
Advanced Techniques with Collections
from collections import OrderedDict, defaultdict
## Ordered dictionary (maintains insertion order)
ordered_dict = OrderedDict([('a', 1), ('b', 2)])
## Default dictionary with default factory
word_count = defaultdict(int)
By mastering these dictionary manipulation techniques, you'll become proficient in handling complex data structures in Python, enhancing your programming skills with LabEx.