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

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

    Starting Python 3.8, and the introduction of assignment expressions (PEP 572) (:= operator), we can capture the condition value dictB.get('hello', None) in a variable value in order to both check if it's not None (as dict.get('hello', None) returns either the associated value or None) and then use it within the body of the condition:

    # dictB = {'hello': 5, 'world': 42}
    # dictA = {}
    if value := dictB.get('hello', None):
      dictA["hello"] = value
    # dictA is now {'hello': 5}
    

提交回复
热议问题