首页 > 解决方案 > 如何从字典中获取第二大值的第一个键?

问题描述

我想从给定的第二大值中获取第一个键。使用这个程序,我可以获得给定值最大的第一个键,但我不知道如何告诉它我想要第二个。另一方面,我必须能够使用 None 值并且它没有通过它们,我能做什么?

def f(x):
    """Return the first ascending KEY ordering of a dictionary
    based on the second biggest value that is given in a dictionary
    biggest value that is given in a dictionary"""

    dict_face = x
    d = max(dict_face, key=dict_face.get)
    print(d)


####
asserts
####
f({'a': 1, 'b': 2, 'c': 2, 'd': 500}) == 'b'
f({'a': 0, 'b': 0, 'c': 2, 'd': 500}) == 'c'
f({'a': None, 'b': None, 'c': None, 'd': 500}) == None

###
output:
d
d
  File "/Users/[...]/dict_biggest_value.py", line 7, in f
    d = max(dict_face, key=dict_face.get)
TypeError: '>' not supported between instances of 'NoneType' and 'NoneType'

谢谢!

标签: pythondictionarykeymaxkey-value

解决方案


我不认为'max'会给你你想要的功能。此外,我认为您必须考虑如果您只有 1 或 0 值会发生什么。你也可以想想你想怎么处理None。我个人将其用作“负无穷大”,即可能的最小值。

我认为你可以写这样的东西:

def second_to_max(input):
    # in here, you track both the max value and the next largest value 
    max = None
    s_max = None
    retVal = ''

    for key, val in input.items():
        # check if val is greater than max, 
        # if so assign max to s_max and val to max
        # and key to retVal
        # You'd have special cases for if max and s_max are None,
        # since you can't actually compare None to an integer

    return retVal

推荐阅读