Add/Remove Items
Add/Remove Items
Adding items to dictionary:
There are two ways to add items to a dictionary.
I. Create a new key and assign a value to it:
Example:
Output:
II. Use the update() method:
The update() method updates the value of the key provided to it if the item already exists in the dictionary, else it creates a new key-value pair.
Example:
Output:
Removing items from dictionary:
There are a few methods that we can use to remove items from dictionary.
clear(): The clear() method removes all the items from the list.
Example:
Output:
pop(): The pop() method removes the key-value pair whose key is passed as a parameter.
Example:
Output:
popitem(): The popitem() method removes the last key-value pair from the dictionary.
Example:
Output:
apart from these three methods, we can also use the del keyword to remove a dictionary item.
Example:
Output:
If key is not provided, then the del keyword will delete the dictionary entirely.
Example:
Output: