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

前端 未结 4 2061
忘掉有多难
忘掉有多难 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")
    
    0 讨论(0)
  • 2021-01-03 19:40

    Use .get(), which if the key is not found, returns None.

    for i in keySet:
        temp = myDict.get(i)
        if temp is not None:
            print temp
            break
    
    0 讨论(0)
  • 2021-01-03 19:50

    You can use myDict.has_key(keyname) as well to validate if the key exists.

    Edit based on the comments -

    This would work only on versions lower than 3.1. has_key has been removed from Python 3.1. You should use the in operator if you are using Python 3.1

    0 讨论(0)
  • 2021-01-03 19:52

    One option if the number of keys is small is to use chained gets:

    value = myDict.get('lastName', myDict.get('firstName', myDict.get('userName')))
    

    But if you have keySet defined, this might be clearer:

    value = None
    for key in keySet:
        if key in myDict:
            value = myDict[key]
            break
    

    The chained gets do not short-circuit, so all keys will be checked but only one used. If you have enough possible keys that that matters, use the for loop.

    0 讨论(0)
提交回复
热议问题