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

前端 未结 4 2078
忘掉有多难
忘掉有多难 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: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.

提交回复
热议问题