Python:如何检查键是否存在并以降序从字典中检索值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17308695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 07:50:15  来源:igfitidea点击:

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

pythondictionarykey-value

提问by Cryssie

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, address, age and so on. Let's say, I only want to get one value (name) - either last name or first name or username but in descending priority like shown below:

我有一本字典,我想根据一些键从中获取一些值。例如,我有一个包含用户名、姓氏、用户名、地址、年龄等信息的字典。比方说,我只想获得一个值(名称)-姓氏或名字或用户名,但按降序排列,如下所示:

(1) last name: if key exists, get value and stop checking. If not, move to next key.

(1) 姓氏:如果key存在,取值并停止检查。如果没有,请移至下一个键。

(2) first name: if key exists, get value and stop checking. If not, move to next key.

(2) 名字:如果key存在,获取值并停止检查。如果没有,请移至下一个键。

(3) username: if key exists, get value or return null/empty

(3) username:如果key存在,取值或者返回null/empty

#my dict looks something like this
myDict = {'age': ['value'], 'address': ['value1, value2'],
          'firstName': ['value'], 'lastName': ['']}

#List of keys I want to check in descending priority: lastName > firstName > userName
keySet = ['lastName', 'firstName', 'userName']

What I tried doing is to get all the possible values and put them into a list so I can retrieve the first element in the list. Obviously it didn't work out.

我尝试做的是获取所有可能的值并将它们放入列表中,以便我可以检索列表中的第一个元素。显然它没有奏效。

tempList = []

for key in keys:
    get_value = myDict.get(key)
    tempList .append(get_value)

Is there a better way to do this without using if else block?

有没有更好的方法来做到这一点而不使用 if else 块?

采纳答案by Peter DeGlopper

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:

但是如果你定义了 keySet,这可能会更清楚:

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 forloop.

链接的gets 不会短路,因此将检查所有密钥,但仅使用一个。如果您有足够多的重要键,请使用for循环。

回答by TerryA

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

使用.get(),如果未找到密钥,则返回None

for i in keySet:
    temp = myDict.get(i)
    if temp is not None:
        print temp
        break

回答by Nikhil Gupta

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

您也可以使用myDict.has_key(keyname)来验证密钥是否存在。

Edit based on the comments -

根据评论进行编辑 -

This would work only on versions lower than 3.1. has_keyhas been removed from Python 3.1. You should use the inoperator if you are using Python 3.1

这仅适用于低于 3.1 的版本。has_key已从 Python 3.1 中删除。in如果您使用的是 Python 3.1,则应使用运算符

回答by olivecoder

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

如果我们将它封装在一个函数中,我们可以使用递归并通过正确命名函数来清楚地说明目的(不确定getAny实际上是否是一个好名字):

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:

然后可以以类似于 dict.get 方法的方式使用它,例如:

getAny(myDict, keySet)

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

甚至在根本找不到密钥的情况下有一个默认结果:

getAny(myDict, keySet, "not found")