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

前端 未结 10 2504
陌清茗
陌清茗 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:34

    Personally, I lean towards the second method (but using has_key):

    if B.has_key("blah"):
      A["blah"] = B["blah"]
    

    That way, each assignment operation is only two lines (instead of 4 with try/except), and any exceptions that get thrown will be real errors or things you've missed (instead of just trying to access keys that aren't there).

    As it turns out (see the comments on your question), has_key is deprecated - so I guess it's better written as

    if "blah" in B:
      A["blah"] = B["blah"]
    

提交回复
热议问题