You can do this:
d.pop("", None)
d.pop(None, None)
Pops dictionary with a default value that you ignore.
Answer from Keith on Stack Overflowdictionary - Silently removing key from a python dict - Stack Overflow
Does the dictionary pop() method return an error if the key is not present?
python - dict.pop versus dict.get on the default return value - Stack Overflow
How can I remove a key from a Python dictionary? - Stack Overflow
If your primary concern is if a key exists within the dictionary, it should be done via 'my_key' in my_dict. .get and .pop as you can imagine serves slightly different purposes. .get is strictly retrieval, and .pop is retrieval and removal. You will want to use the respective method that best suit your use case, and employ a default value if you don't need to handle a KeyError.
As for the reason of why .pop doesn't use a default value by default, it is because that the operation expects to also remove a key from the dictionary. If the operation was completed successfully without raising an error, one might erroneously expect the key to be removed from the dictionary as well.
For .get, the method exists specifically as a alternative to provide a default value over the __getitem__ method, which you usually see the syntax as my_dict['my_key']. The latter of which, will raise a KeyError if the key doesn't exist.
get exists, in some sense, in two varieties: one raises a KeyError, the other doesn't.
>>> {}['my_key']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'my_key'
>>> {}.get('my_key')
>>>
pop, on the other hand, isn't an error-free version of another operation that raises a KeyError, so it's used in both situations: raising a KeyError by default, but returning a default value if requested.
>>> {}.pop('my_key')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'my_key'
>>> {}.pop('my_key', 3)
3
To delete a key regardless of whether it is in the dictionary, use the two-argument form of dict.pop():
my_dict.pop('key', None)
This will return my_dict[key] if key exists in the dictionary, and None otherwise. If the second parameter is not specified (i.e. my_dict.pop('key')) and key does not exist, a KeyError is raised.
To delete a key that is guaranteed to exist, you can also use
del my_dict['key']
This will raise a KeyError if the key is not in the dictionary.
Specifically to answer "is there a one line way of doing this?"
if 'key' in my_dict: del my_dict['key']
...well, you asked ;-)
You should consider, though, that this way of deleting an object from a dict is not atomic—it is possible that 'key' may be in my_dict during the if statement, but may be deleted before del is executed, in which case del will fail with a KeyError. Given this, it would be safest to either use dict.pop or something along the lines of
try:
del my_dict['key']
except KeyError:
pass
which, of course, is definitely not a one-liner.
The pop method of dicts (like self.data, i.e. {'a':'aaa','b':'bbb','c':'ccc'}, here) takes two arguments -- see the docs
The second argument, default, is what pop returns if the first argument, key, is absent.
(If you call pop with just one argument, key, it raises an exception if that key's absent).
In your example, print b.pop('a',{'b':'bbb'}), this is irrelevant because 'a' is a key in b.data. But if you repeat that line...:
b=a()
print b.pop('a',{'b':'bbb'})
print b.pop('a',{'b':'bbb'})
print b.data
you'll see it makes a difference: the first pop removes the 'a' key, so in the second pop the default argument is actually returned (since 'a' is now absent from b.data).
So many questions here. I see at least two, maybe three:
- What does pop(a,b) do?/Why are there a second argument?
- What is
*argsbeing used for?
The first question is trivially answered in the Python Standard Library reference:
pop(key[, default])
If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised.
The second question is covered in the Python Language Reference:
If the form “*identifier” is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form “**identifier” is present, it is initialized to a new dictionary receiving any excess keyword arguments, defaulting to a new empty dictionary.
In other words, the pop function takes at least two arguments. The first two get assigned the names self and key; and the rest are stuffed into a tuple called args.
What's happening on the next line when *args is passed along in the call to self.data.pop is the inverse of this - the tuple *args is expanded to of positional parameters which get passed along. This is explained in the Python Language Reference:
If the syntax *expression appears in the function call, expression must evaluate to a sequence. Elements from this sequence are treated as if they were additional positional arguments
In short, a.pop() wants to be flexible and accept any number of positional parameters, so that it can pass this unknown number of positional parameters on to self.data.pop().
This gives you flexibility; data happens to be a dict right now, and so self.data.pop() takes either one or two parameters; but if you changed data to be a type which took 19 parameters for a call to self.data.pop() you wouldn't have to change class a at all. You'd still have to change any code that called a.pop() to pass the required 19 parameters though.