Google News
logo
Python - Interview Questions
How Do You Delete Elements Of A Dictionary In Python?
We can delete a key in a dictionary by using the del() method.
 
>>> site_stats = {'site': 'freetimelearning.com', 'traffic': 10000, "type": "organic"}
>>> del site_stats["type"]
>>> print(site_stats)
{'site': 'google.co.in', 'traffic': 1000000}

Another method, we can use is the pop() function. It accepts the key as the parameter. Also, a second parameter, we can pass a default value if the key doesn’t exist.
 
>>> site_stats = {'site': 'freetimelearning.com', 'traffic': 10000, "type": "organic"}
>>> print(site_stats.pop("type", None))
organic
>>> print(site_stats)
{'site': 'freetimelearning.com', 'traffic': 10000}
Advertisement