Add/Remove Items
Adding items to a dictionary:
There are two common ways to add items to a dictionary.
1. Create a new key and assign a value to it:
Example:
info = {'name': 'Karan', 'age': 19, 'eligible': True}
print(info)
info['DOB'] = 2001
print(info)Output:
{'name': 'Karan', 'age': 19, 'eligible': True}
{'name': 'Karan', 'age': 19, 'eligible': True, 'DOB': 2001}2. Use the update() method:
The update() method updates the value of an existing key, and if the key does not exist, it creates a new key-value pair.
Example:
info = {'name': 'Karan', 'age': 19, 'eligible': True}
print(info)
info.update({'age': 20})
info.update({'DOB': 2001})
print(info)Output:
{'name': 'Karan', 'age': 19, 'eligible': True}
{'name': 'Karan', 'age': 20, 'eligible': True, 'DOB': 2001}Removing items from dictionary:
There are several methods available to remove items from a dictionary.
clear():
The clear() method removes all the items from the dictionary.
Example:
info = {'name': 'Karan', 'age': 19, 'eligible': True}
info.clear()
print(info)Output:
{}pop():
The pop() method removes the key-value pair whose key matches the parameter passed.
Example:
info = {'name': 'Karan', 'age': 19, 'eligible': True}
info.pop('eligible')
print(info)Output:
{'name': 'Karan', 'age': 19}popitem():
The popitem() method removes the last inserted key-value pair from the dictionary.
Example:
info = {'name': 'Karan', 'age': 19, 'eligible': True, 'DOB': 2003}
info.popitem()
print(info)Output:
{'name': 'Karan', 'age': 19, 'eligible': True}Apart from these three methods, we can also use the del keyword to remove a dictionary item.
Example:
info = {'name': 'Karan', 'age': 19, 'eligible': True, 'DOB': 2003}
del info['age']
print(info)Output:
{'name': 'Karan', 'eligible': True, 'DOB': 2003}If a key is not provided, the del keyword will delete the entire dictionary.
Example:
info = {'name': 'Karan', 'age': 19, 'eligible': True, 'DOB': 2003}
del info
print(info)Output:
NameError: name 'info' is not defined