If I set a default value on a dict, is it possible to get the default value back after its been overwritten?
Like this:
dd = {}
dd.setdefault('beverage':'A nice cup of tea')
...
dd['beverage'] = 'Yellow urine'
...
if dd['beverage'] not in list_of_valid_beverages:
# If the beverage has been contaminated revert to default.
# Something like any of the following?
dd['beverage'] = dd.getdefault('beverage')
dd['beverage'].clear()
del dd['beverage']
...
print dd['beverage']
My guess is that this is not possible with an ordinary dict. Ones the statement
dd[‘beverage’] = ‘Yellow urine’
is executed the tea is forever lost. But it would be a nice feature 🙂
Anyone with deeper knowledge about this?
No, it’s not possible. All
setdefaultdoes is the following logic:It does not treat the “default” value specially, and doesn’t store it anywhere other than the location that you’re overwriting.
If you want a set of persistent defaults, you’re best off just keeping a separate
dictof the default values.