Python:如何检查键是否存在以及如何从字典中检索优先级降序的值 [英] Python: How to check if keys exists and retrieve value from Dictionary in descending priority
问题描述
我有一个字典,我想根据一些键从字典中获取一些值.例如,我为用户提供了一个词典,其中包含他们的名字,姓氏,用户名,地址,年龄等.假设,我只想获取一个值(名称)-姓氏,名字或用户名,但优先级降级,如下所示:
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)姓:如果密钥存在,则获取值并停止检查.如果不是,请移至下一个键.
(1) last name: if key exists, get value and stop checking. If not, move to next key.
(2)名:如果键存在,则获取值并停止检查.如果不是,请移至下一个键.
(2) first name: if key exists, get value and stop checking. If not, move to next key.
(3)用户名:如果键存在,则获取值或返回null/empty
(3) username: if key exists, get value or return 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)
有没有不使用if else块的更好的方法吗?
Is there a better way to do this without using if else block?
推荐答案
如果键的数量较少,则可以选择使用链式获取:
One option if the number of keys is small is to use chained gets:
value = myDict.get('lastName', myDict.get('firstName', myDict.get('userName')))
但是,如果您定义了keySet,这可能会更清楚:
But if you have keySet defined, this might be clearer:
value = None
for key in keySet:
if key in myDict:
value = myDict[key]
break
链接的get
不会短路,因此将检查所有按键,但仅会使用其中一个.如果有足够重要的键,请使用for
循环.
The chained get
s 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.
这篇关于Python:如何检查键是否存在以及如何从字典中检索优先级降序的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!