python - 在字典列表中查找最大值

标签 python data-structures

给定一个数据结构:

   [
    {'id':0, 'items': 
      [
       {'id': 0,  name: "Tom1", age: 10}, 
       {'id': 0, name: "Mark1", age: 15}, 
       {'id': 0, name: "Pam1", age: 17}
      ]
    },
    {'id':1, 'items': 
      [
       {'id': 1,  name: "Tom12", age: 8}, 
       {'id': 1, name: "Mark12", age: 3}, 
       {'id': 1, name: "Pam12", age: 2}
      ]
    },

    {'id':2, 'items': 
      [
       {'id': 2,  name: "Tom13", age: 55}, 
       {'id': 2, name: "Mark13", age: 66}, 
       {'id': 2, name: "Pam13", age: 77}
      ]
    },
  ]

我想在每个字典中找到一个年龄具有最大值的项目并选择它。我该如何实现?

最佳答案

试试这个:

for dVals in yourData:
    print max(dVals['items'], key=lambda x:x['age'])

或单行:

print [max(dVals['items'], key=lambda x: x['age']) for dVals in yourData]

{'id': 0, 'age': 17, 'name': 'Pam1'}
{'id': 1, 'age': 8, 'name': 'Tom12'}
{'id': 2, 'age': 77, 'name': 'Pam13'}

关于python - 在字典列表中查找最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13262382/

相关文章:

c - 是否有任何 sys/queue.h 宏用于合并两个 TAILQ

algorithm - 最小化加权和

performance - 手指树(Data.Sequence)与绳索(Data.Rope)(Haskell,或一般情况下)

data-structures - 看起来像保龄球瓶的数据结构的名称是什么?

python - Firebase Firestore : get generated ID of document (Python)

python - 如何替换 pandas 数据框列中由后面的列定义的变量子字符串?

python - 错误 : Setup script exited with error: command 'i586-linux-gnu-gcc' failed with exit status 1

excel - 日期重叠 : generalized way to split the dates to get the overlapping interval?

python - Predict_proba 不适用于我的高斯混合模型(sklearn,python)

python - Pygame 已安装;然而,python 终端显示 "No module named ' pygame' "(Ubuntu 20.04.1)