Dictionary Modification
Dictionaries are mutable, allowing dynamic changes to their contents.
1. Adding New Key-Value Pairs
Assign a value to a new key using square bracket notation.
python config = {'mode': 'default'} config['port'] = 8080 # Add new key 'port' config['timeout'] = 300 print(config) # {'mode': 'default', 'port': 8080, 'timeout': 300}
2. Modifying Existing Values
Assign a new value to an existing key.
python user = {'name': 'Alice', 'status': 'offline'} user['status'] = 'online' # Overwrite the 'status' value print(user) # {'name': 'Alice', 'status': 'online'}
3. Removing Key-Value Pairs
a) del Statement
Deletes the pair by key.
python del user['status'] print(user) # {'name': 'Alice'}
b) .pop() Method
Removes the item with the given key and returns the corresponding value (similar to list pop).
python data = {'a': 1, 'b': 2, 'c': 3} value_b = data.pop('b') print(f"Removed value: {value_b}") # 2 print(data)
c) .clear() Method
Removes all items from the dictionary.
python data.clear() print(data) # {}