dict.get() - default arg evaluated even upon success

后端 未结 6 2019
有刺的猬
有刺的猬 2020-12-05 18:08

Why is the default in dict.get(key[, default]) evaluated even if the key is in the dictionary?

>>> key = \'foo\'
>>> a={}
>>> b={k         


        
6条回答
  •  温柔的废话
    2020-12-05 18:41

    use this instead

    x = b.get(key) or a.get(key)
    

    or and and are short circuit operators, so if b has the key it won't look at a. But problems will arise if you have falsy values in b. If that is the case you can do:

    x = b[key] if key in b else a.get(key)
    

提交回复
热议问题