Delete a dictionary item if the key exists [duplicate]

Digital Marketing Facebook Marketing API 3 years ago

5.91K 1 0 0 0

_x000D_ _x000D_ _x000D_ This question already has an answer here:_x000D_ _x000D_ _x000D_ How to remove a key from a Python dictionary?_x000D_ _x000D_ 11 answers_x000D_ _x000D_ _x000D_ _x000D_ _x000D_ Is there any other way to delete an item in a dictionary only if the given key exists, other than: if key in mydict: del mydict[key] The scenario is that I'm given a collection of keys to be removed from a given dictionary, but I am not certain if all of them exist in the dictionary. Just in case I miss a more efficient solution.

User submissions are the sole responsibility of contributors, with TuteeHUB disclaiming liability for accuracy, copyrights, or consequences of use; content is for informational purposes only and not professional advice.

Answers (1)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 3 years ago
_x000D_ You can use dict.pop: mydict.pop("key", None) Note that if the second argument, i.e. None is not given, KeyError is raised if the key is not in the dictionary. Providing the second argument prevents the conditional exception.
0 views
0 shares

No matter what stage you're at in your education or career, TuteeHUB will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.

Similar Forum


Q

What are the best SEO tools for a personal website? What website or tools should I use to build and...

What are the best SEO tools for a personal website? What website or tools should I use to build and...
Q

Why is keyword research important?

Why is keyword research important?
Q

What is SEO ?

What is SEO ?