根据Python中的条件在字典中返回最大值的键 [英] Return the key of the maximum value in a dictionary base on criteria in Python

查看:264
本文介绍了根据Python中的条件在字典中返回最大值的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下字典:

d = {'a': {'0': 'London', '1': 'Athens', '2': 'Paris', '3': 'London'},
 'b': {'0': 1, '1': 2, '2': 3, '3': 2}}

d['a']d['b']中的键相同.

我想返回子词典d['b']中具有最高值的键,而键在子词典d['a']中具有特定值.

I would like to return the key with the highest value in sub-dictionary d['b'] where it has a specific value in sub-dictionary d['a'].

例如,如果我将输入设置为'London',它应该返回'3',因为'London'在键'0''3'中,并且这些键的最大值在字典'b'中在键'3'下.

For example, if I set as an input 'London', it should return '3', because 'London' is in keys '0' and '3', and the highest values for these keys in dictionary 'b' is under key '3'.

我该怎么做?

推荐答案

您有一些选择.假设您不想使用更合适的结构,则可以从找到与London:

You have a few options. Assuming you don't want to use a more suitable structure, you can start by finding the keys matching London:

d = {
     'a': {'0': 'London', '1': 'Athens', '2': 'Paris', '3': 'London'},
     'b': {'0': 1, '1': 2, '2': 3, '3': 2}
}
a = d['a']
b = d['b']

keys = [k for k in a if a[k] == 'London']

然后,您可以在结果上运行max:

Then, you can run max on the result:

max(keys, key=lambda k: b[k])

单线:

max((k for k in a if a[k] == 'London'), key=lambda k: b[k])

此方法的问题在于您正在按值查找字典,这在很大程度上与提出字典的提议背道而驰.如果您可以自由修改字典a,请对其进行反转:

The problem with this approach is that you are looking up in a dictionary by value, which largely defeats the propose of having a dictionary. If you have the freedom to modify your dictionary a, reverse it:

from collections import defaultdict
a_better = defaultdict(list)
for v, k in a.items():
    a_better[k].append(v)

现在查找更加简单:

max(a_better['London'], key=lambda k: b[k])

这篇关于根据Python中的条件在字典中返回最大值的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆