获取嵌套字典中最大值的记录

我想编写一个函数来检查字典并返回两个键(“名称”和“成本”)以获取“食物”中最大成本的记录:

[{'age': 'Dark',
  'armor': '0/1',
  'attack': 4,
  'build_time': 21,
  'cost': {'Food': 60, 'Gold': 20},
  'created_in': 'https://age-of-empires-2-api.herokuapp.com/api/v1/structure/barracks',
  'description': 'Basic infantry swordsman. Quick and cheap to create',
  'expansion': 'Age of Kings',
  'hit_points': 40,
  'id': 15,
  'line_of_sight': 4,
  'movement_rate': 0.9,
  'name': 'Militia',
  'reload_time': 2.0},
 {'age': 'Dark',
  'armor': '0/0',
  'build_time': 30,
  'cost': {'Food': 50},
  'created_in': 'https://age-of-empires-2-api.herokuapp.com/api/v1/structure/castle',
  'description': 'Cannot be produced so the cost and build time just for the sake of interest',
  'expansion': 'Age of Kings',
  'hit_points': 75,
  'id': 20,
  'line_of_sight': 6,
  'movement_rate': 1.32,
  'name': 'King'}]

这里是民兵和 ({'Food': 60, 'Gold': 20})

所以我试过了

def filter_by_age(filtered_data, age):
  return sorted(filtered_data, key=filtered_data['cost']['food].get, reverse=True)[:1]['name', 'cost']

但我得到了:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-22-262726f1a4ab> in <module>()
      1 def filter_by_age(filtered_data):
      2     return sorted(filtered_data, key=filtered_data['cost']['food'].get, reverse=True)[:1]['name', 'cost']
----> 3 filter_by_age(filter_by_age(data, 'Dark'))

TypeError: filter_by_age() takes 1 positional argument but 2 were given

回答

您可以maxkey. seq是您的输入列表。

res = max(seq, key=lambda x:x['cost']['Food'])
print(res['name'], res['cost'])

输出

Militia {'Food': 60, 'Gold': 20}


以上是获取嵌套字典中最大值的记录的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>