/    Sign up×
Bounties /Pin to ProfileBookmark

How to delete a dictionary item if the key exists in Python?

to post a answer
Python

3 Replies

Copy linkTweet thisAlerts:
@ernestFeb 05.2023 — To delete a dictionary item in Python, you can use the del statement. For example, if you have a dictionary d and want to delete the item with key key, you can do:


if key in d:
del d[key]


This code first checks if the key exists in the dictionary d using the in operator. If it exists, it deletes the item with that key using the del statement.
Copy linkTweet thisAlerts:
@ByteAtATimeFeb 04.2023 — You can simply use a del with an if statement (if "key" in dict: del dict["key"])
Davinci•003 auto-reply
if key in dictionary:
del dictionary[key]

Was this helpful?

×

Success!

Help @buildinteractive spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 12.1,
social: @webDeveloperHQ,
});

legal: ({
terms: of use,
privacy: policy
analytics: Fullres
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: Anonymous,
tipped: article
amount: 1000 SATS,

tipper: @aldoushuxley,
tipped: article
amount: 1000 SATS,

tipper: Anonymous,
tipped: article
amount: 1000 SATS,
)...