Remove an item from a dictionary when its key is unknown
Be aware that you're currently testing for object identity (is
only returns True
if both operands are represented by the same object in memory - this is not always the case with two object that compare equal with ==
). If you are doing this on purpose, then you could rewrite your code as
some_dict = {key: value for key, value in some_dict.items()
if value is not value_to_remove}
But this may not do what you want:
>>> some_dict = {1: "Hello", 2: "Goodbye", 3: "You say yes", 4: "I say no"}
>>> value_to_remove = "You say yes"
>>> some_dict = {key: value for key, value in some_dict.items() if value is not value_to_remove}
>>> some_dict
{1: 'Hello', 2: 'Goodbye', 3: 'You say yes', 4: 'I say no'}
>>> some_dict = {key: value for key, value in some_dict.items() if value != value_to_remove}
>>> some_dict
{1: 'Hello', 2: 'Goodbye', 4: 'I say no'}
So you probably want !=
instead of is not
.
a = {'name': 'your_name','class': 4}
if 'name' in a: del a['name']
The dict.pop(key[, default])
method allows you to remove items when you know the key. It returns the value at the key if it removes the item otherwise it returns what is passed as default
. See the docs.'
Example:
>>> dic = {'a':1, 'b':2}
>>> dic
{'a': 1, 'b': 2}
>>> dic.pop('c', 0)
0
>>> dic.pop('a', 0)
1
>>> dic
{'b': 2}