`mydict.get(x, x)`等价于`mydict.get(x)或x`吗?

问题描述 投票:0回答:1

偶尔使用字典替换值时,

.get(x, x)
.get(x) or x
等价吗?

例如:

def current_brand(brand_name):
    rebrands = {
        "Marathon":    "Snickers",
        "Opal Fruits": "Starburst",
        "Jif":         "Cif",
        "Thomson":     "TUI",
    }
    
    return rebrands.get(brand_name, brand_name)
    # or
    return rebrands.get(brand_name) or brand_name

    # this is forbidden - cannot use `default` keyword argument here
    return rebrands.get(brand_name, default=brand_name)

assert current_brand("Jif") == "Cif"
assert current_brand("Boots") == "Boots"

我认为

.get(x) or x
更清楚,但这很大程度上是一个观点问题,所以我很好奇是否存在我没有发现的技术优点或缺点。

python python-3.x dictionary
1个回答
4
投票

'恐怕不会!如果您的值为 Falsey,

or
将会短路,因此在很多值中,两个语句的行为会有所不同。

my_dict = {
    'foo': 0,
    'bar': "",
    'baz': [],
}

x = 'foo'
print(repr(my_dict.get(x, x)))
print(repr(my_dict.get(x) or x))
© www.soinside.com 2019 - 2024. All rights reserved.