简体   繁体   English

我可以获取setdefault设置的默认值

[英]Can I get the default value set by setdefault

If I set a default value on a dict, is it possible to get the default value back after its been overwritten? 如果我在dict上设置了默认值,是否可以在覆盖后恢复默认值?

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. 我的猜测是普通的dict是不可能的。 Ones the statement 声明

dd['beverage'] = 'Yellow urine' dd ['drink'] ='黄尿'

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 setdefault does is the following logic: 所有setdefault都是以下逻辑:

if key not in the_dict:
    the_dict[key] = value
return the_dict[key]

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 dict of the default values. 如果你想要一组持久性默认值,那么最好只保留一个默认值的单独dict

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在特定列表中使用setdefault设置默认值 - Set default values with setdefault within specific list 为什么setdefault在设置密钥时会评估默认值? - Why does setdefault evaluate default when key is set? dict.setdefault将一个额外的(默认值)项添加到值列表中 - dict.setdefault appends one extra (default?) item into the value list 如何在eve中设置默认的datetime值? - How can I set a default datetime value in eve? 我可以在字段构造函数之外设置 StringField 的默认值吗? - Can I set a StringField's default value outside the field constructor? 如何使用装饰器为函数参数设置默认值? - How can i set a default value for a function parameter with a decorator? 我可以在 python 中设置 Prometheus 标签的默认值吗? - Can I set a default value of Prometheus labels in python? 我可以为 python 中的任意参数设置默认值吗? - Can I set a default value for an arbitrary argument in python? 如何为记录类数据对象的枚举属性设置默认值? - How can I set a default value for an enum attribute of a recordclass dataobject? 防止评估现有键在dictionary.get或dictionary.setdefault中的默认功能 - Prevent evaluating default function in dictionary.get or dictionary.setdefault for existing keys
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM