delete one dictionnary key in python

To delete a dictionary key in Python, you can use the pop() method that removes and returns an element from a dictionary based on the given key. Here's an example:

main.py
data = {"name": "John", "age": 30, "city": "New York"}

# Delete the "age" key
data.pop("age")

# The new dictionary after deletion
print(data)  # Output: {"name": "John", "city": "New York"}
192 chars
8 lines

Alternatively, you can use the del statement with the key to delete the key-value pair from the dictionary:

main.py
data = {"name": "John", "age": 30, "city": "New York"}

# Delete the "age" key
del data["age"]

# The new dictionary after deletion
print(data)  # Output: {"name": "John", "city": "New York"}
192 chars
8 lines

Note that if you try to delete a key that does not exist in the dictionary, both pop() and del statements will raise a KeyError. To avoid this, you can use the in keyword to check if the key exists in the dictionary before deleting it.

gistlibby LogSnag