To clear all key-value pairs from a dictionary in Python, you can use the `clear` method. This method removes all elements from the dictionary, making it empty.
We can clear all key-value pairs from a dictionary in Python using the `clear` method. This example demonstrates how to remove all elements from the dictionary and print the dictionary contents before and after the clearing operation.
For example,
my_dict
with integer keys and string values.my_dict = {
1: 'One',
2: 'Two',
3: 'Three'
}
# Print the dictionary contents before clearing
print('Dictionary contents before clearing:')
for key, value in my_dict.items():
print(f'Key: {key}, Value: {value}')
# Clear all key-value pairs from the dictionary
my_dict.clear()
# Print the dictionary contents after clearing
print('Dictionary contents after clearing:')
for key, value in my_dict.items():
print(f'Key: {key}, Value: {value}')
Dictionary contents before clearing: Key: 1, Value: One Key: 2, Value: Two Key: 3, Value: Three Dictionary contents after clearing:
We can clear all key-value pairs from a dictionary in Python and confirm that it is empty by checking the length of the dictionary. This example demonstrates how to clear the dictionary and verify that it is empty.
For example,
my_dict
with integer keys and string values.my_dict = {
1: 'One',
2: 'Two',
3: 'Three'
}
# Print the dictionary contents before clearing
print('Dictionary contents before clearing:')
for key, value in my_dict.items():
print(f'Key: {key}, Value: {value}')
# Clear all key-value pairs from the dictionary
my_dict.clear()
# Confirm the dictionary is empty
if len(my_dict) == 0:
print('The dictionary is now empty.')
else:
print('The dictionary is not empty.')
Dictionary contents before clearing: Key: 1, Value: One Key: 2, Value: Two Key: 3, Value: Three The dictionary is now empty.
In this tutorial, we learned How to Clear all Key-Value Pairs from a Dictionary in Python language with well detailed examples.