python - 如何在键不一致的字典列表中查找值

标签 python python-2.7 dictionary

这里,我有一个字典列表,我需要使用值查找对象。

people = [
   {'name': mifta}
   {'name': 'khaled', 'age':30},
   {'name': 'reshad', 'age':31}
]

我想通过“age”键查找值为 30 的位置。我可以通过以下方式做到这一点

for person in people:
  if person.get('age'):
    if person['age'] == 30:

有没有更好的方法来做到这一点而不需要大量的 if else ?

最佳答案

您可以只使用 dict.get() 一次,而不使用 person['age'],它允许您在 key 丢失时提供默认值,所以你可以尝试这个:

dict.get

Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError

people = [
   {'name': 'mifta'},
   {'name': 'khaled', 'age':30},
   {'name': 'reshad', 'age':31}
]    
for person in people:
    if person.get('age',0)==30:
        print(person)

关于python - 如何在键不一致的字典列表中查找值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43198765/

相关文章:

python - 如何将对象属性作为函数参数传递给 lambda 函数?

python - 在 C 中嵌入 Python : Error when attempting to call Python code in a C callback called by Python code

python-2.7 - 将圆形 float 转换为字符串 Pandas 的问题

python - 类型错误:不支持的操作数类型 - : 'list' 和 'list'

python - reshape 字典键

python - 对保存列表的变量使用算术运算符

python atexit错误: the first argument must be callable

iPhone : Top Navigation bar push the Google logo down the screen

java - 使用 JPA 注释映射 java.util.Map 时,键和值列名称会被覆盖

python - 如何防止从 celery 任务中重复记录异常