简体   繁体   English

dict.get(key, default) 与 dict.get(key) 或默认值

[英]dict.get(key, default) vs dict.get(key) or default

Is there any difference (performance or otherwise) between the following two statements in Python? Python中的以下两个语句之间有什么区别(性能或其他)?

v = my_dict.get(key, some_default)

vs对比

v = my_dict.get(key) or some_default

There is a huge difference if your value is false-y :如果您的值是false-y ,则存在巨大差异:

>>> d = {'foo': 0}
>>> d.get('foo', 'bar')
0
>>> d.get('foo') or 'bar'
'bar'

You should not use or default if your values can be false-y.应该使用or default ,如果您的值可以是假的-Y。

On top of that, using or adds additional bytecode;最重要的是,使用or添加额外的字节码; a test and jump has to be performed.必须执行测试和跳转。 Just use dict.get() , there is no advantage to using or default here.只需使用dict.get() ,在这里使用or default没有优势。

There is another difference: if some_default is not a value but an expression, it must be evaluated before being passed to dict.get() , whereas with or the expression will not be evaluated if you get a truthy value out of your dictionary.还有另一个区别:如果some_default不是值而是表达式,则必须在传递给dict.get()之前对其进行评估,而如果您从字典中获得真值,则不会评估 with or表达式。 For example:例如:

v = my_dict.get(key, do_something_that_takes_a_long_time())  # function always called
v = my_dict.get(key) or do_something_that_takes_a_long_time()  # function only called if needed

So while it is true that it isn't safe to use or if your dictionary can contain falsey values, there can potentially be a performance advantage.因此,虽然它确实不安全, or您的字典可能包含假值,但可能会带来性能优势。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM