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.

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:")

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

print("\nUpdated Dictionary:")

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: Rakesh
Author Info:

Rakesh is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

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