`if key in dict` vs. `try/except` - which is more readable idiom?

前端 未结 10 2487
陌清茗
陌清茗 2020-11-28 06:19

I have a question about idioms and readability, and there seems to be a clash of Python philosophies for this particular case:

I want to build dictionary A from dict

10条回答
  •  时光取名叫无心
    2020-11-28 06:27

    I think the second example is what you should go for unless this code makes sense:

    try:
        A["foo"] = B["foo"]
        A["bar"] = B["bar"]
        A["baz"] = B["baz"]
    except KeyError:
        pass
    

    Keep in mind that code will abort as soon as there is a key that isn't in B. If this code makes sense, then you should use the exception method, otherwise use the test method. In my opinion, because it's shorter and clearly expresses the intent, it's a lot easier to read than the exception method.

    Of course, the people telling you to use update are correct. If you are using a version of Python that supports dictionary comprehensions, I would strongly prefer this code:

    updateset = {'foo', 'bar', 'baz'}
    A.update({k: B[k] for k in updateset if k in B})
    

提交回复
热议问题