如果我在字典上设置默认值,是否可以在覆盖后恢复默认值?
像这样:
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']
我的猜测是,这对于普通的 dict 是不可能的。那些声明
dd['饮料'] = '黄色尿液'
被处决,茶就永远消失了。但这将是一个不错的功能:-)
有对此有更深入了解的人吗?