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

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

    Direct quote from Python performance wiki:

    Except for the first time, each time a word is seen the if statement's test fails. If you are counting a large number of words, many will probably occur multiple times. In a situation where the initialization of a value is only going to occur once and the augmentation of that value will occur many times it is cheaper to use a try statement.

    So it seems that both options are viable depending from situation. For more details you might like to check this link out: Try-except-performance

提交回复
热议问题