lled lled - 1 year ago 88
Python Question

Dictionary: Revert/remove setdefault

I currently have an object passed to my callback which is a dictionary and which I have to return.

The invoker called

obj.setdefault("Server", "Something")
on the dictionary so that it has a default value even if the key/value pair does not exist.

How can I revert/remove that
(remove the default value)? I mean I simply don't want that key/value pair in the dict and it seems that it doesn't have complications if the key doesn't exit, but it is always added because of the default.

Answer Source

The setdefault method sets the value of the Server key to Something (as long as the Server key is not already in the dictionary). You can simply delete the Server key from the dictionary:

if 'Server' in obj: del obj['Server']

If you don't want to remove the server key when its value is different from Something, do:

if obj['Server'] == 'Something': del obj['Server']

However, you cannot tell whether the value of Server was added to the dictionary as a default value or as a plain setting of a key-value pair. That's because after invoking setdefault, the dictionary holds the key-value pair without any indication as to how it was added.


>>>d = {}
>>>d.setdefault("Server", "Something")
{'Server': 'Something'}
>>>del d['Server']