Python Program to Remove Elements from Dictionary
# Program to show how to remove elements from a dictionary
# initializing a dictionary
Dictionary = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
# removing a key:value pair from the dictionary using pop()
Dictionary.pop(4)
print("\nAfter removing a key using pop(): ")
print(Dictionary)
# remove any item at random using popitem()
Dictionary.popitem()
print("\nAfter removing an arbitrary key: ")
print(Dictionary)
# remove all the items present in dictionary
print("\nAfter removing all the items: ")
Dictionary.clear()
print(Dictionary)
# deleting the dictionary variable
del Dictionary
# Printing dictionary after deleting it
try:
print(Dictionary)
except:
print('No dictionary of the given name')
Output:
After removing a key using pop():
{1: 'a', 2: 'b', 3: 'c', 5: 'e'}
After removing an arbitrary key:
{1: 'a', 2: 'b', 3: 'c'}
After removing all the items:
{}
No dictionary of the given name
