Python: How to check if keys exists and retrieve value from Dictionary in descending priority

前端 未结 4 2062
忘掉有多难
忘掉有多难 2021-01-03 19:07

I have a dictionary and I would like to get some values from it based on some keys. For example, I have a dictionary for users with their first name, last name, username, ad

4条回答
  •  没有蜡笔的小新
    2021-01-03 19:30

    If we encapsulate that in a function we could use recursion and state clearly the purpose by naming the function properly (not sure if getAny is actually a good name):

    def getAny(dic, keys, default=None):
        return (keys or default) and dic.get(keys[0], 
                                             getAny( dic, keys[1:], default=default))
    

    or even better, without recursion and more clear:

    def getAny(dic, keys, default=None):
        for k in keys: 
            if k in dic:
               return dic[k]
        return default
    

    Then that could be used in a way similar to the dict.get method, like:

    getAny(myDict, keySet)
    

    and even have a default result in case of no keys found at all:

    getAny(myDict, keySet, "not found")
    

提交回复
热议问题