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

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

    There is also a third way that avoids both exceptions and double-lookup, which can be important if the lookup is expensive:

    value = B.get("blah", None)
    if value is not None: 
        A["blah"] = value
    

    In case you expect the dictionary to contain None values, you can use some more esoteric constants like NotImplemented, Ellipsis or make a new one:

    MyConst = object()
    def update_key(A, B, key):
        value = B.get(key, MyConst)
        if value is not MyConst: 
            A[key] = value
    

    Anyway, using update() is the most readable option for me:

    a.update((k, b[k]) for k in ("foo", "bar", "blah") if k in b)
    

提交回复
热议问题