Removing a key from Python Dict


In order to delete a key from a dictionary (dist) data structure you would need to make use of the del keyword. You can delete or remove an object or element from memory using del keyword.


Example:
countries_capitals = {
    'USA': 'Washington, D.C.',
    'Canada': 'Ottawa',
    'Brazil': 'Brasília',
    'India': 'New Delhi',
    'Australia': 'Canberra',
    'Nigeria': 'Abuja',
    'Russia': 'Moscow',
    'China': 'Beijing',
    'Egypt': 'Cairo',
    'South Africa': 'Pretoria'
}

print("Original Dictionary:")
print(countries_capitals)

# Remove a key-value pair from the dict
del countries_capitals['Russia']

print("\nUpdated Dictionary:")
print(countries_capitals)

Output:
Original Dictionary:
{'USA': 'Washington, D.C.', 'Canada': 'Ottawa', 'Brazil': 'Brasília', 'India': 'New Delhi', 
'Australia': 'Canberra', 'Nigeria': 'Abuja', 'Russia': 'Moscow', 'China': 'Beijing',
'Egypt': 'Cairo', 'South Africa': 'Pretoria'} Updated Dictionary: {'USA': 'Washington, D.C.', 'Canada': 'Ottawa', 'Brazil': 'Brasília', 'India': 'New Delhi',
'Australia': 'Canberra', 'Nigeria': 'Abuja', 'China': 'Beijing',
'Egypt': 'Cairo', 'South Africa': 'Pretoria'}

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap