in Python by
How Do You Delete Elements Of A Dictionary In Python?

1 Answer

0 votes
by
We can delete a key in a dictionary by using the del() method.

>>> site_stats = {'site': 'tecbeamers.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': 'tecbeamers.com', 'traffic': 10000, "type": "organic"}

>>> print(site_stats.pop("type", None))

organic

>>> print(site_stats)

{'site': 'tecbeamers.com', 'traffic': 10000}

Related questions

0 votes
asked Jan 10, 2021 in Python by rajeshsharma
0 votes
asked Jan 1, 2021 in Python by SakshiSharma
0 votes
asked Dec 14, 2019 in Python by sharadyadav1986
...