【问题标题】:how can I get the first key of the second biggest value from a dictionary?如何从字典中获取第二大值的第一个键?
【发布时间】:2021-10-16 20:55:44
【问题描述】:

我想从给定的第二大值中获取第一个键。使用这个程序,我可以获得给定值最大的第一个键,但我不知道如何告诉它我想要第二个。另一方面,我必须能够使用 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'

谢谢!

【问题讨论】:

  • 所以输出应该是c, c和???
  • 不,输出应该是 b, c y none。
  • 为什么要列出 4 件事?您的整个问题尚不清楚。 f(…) == Xs 是什么意思?
  • 是程序必须通过的断言
  • @CarmenTur 你的函数打印了一些东西但不返回任何东西(即,使用return 语句)。因此,您的所有测试都等效于None == 'b'None == 'c' 等。要进行比较,您必须将 print(d) 替换为 return d

标签: python dictionary key max key-value


【解决方案1】:

如果最大值重复怎么办?

话虽如此,一种方法可能是:

values_list = list(dict_face.values())
largest = max(values_list)
values_list.remove(largest)
second_largest = max(values_list)

for k,v in dict_face.items():
  if v == second_largest:
    return k

【讨论】:

  • 你还在用 Python 2 吗?
  • No... values_list.remove(largest) AttributeError: 'dict_values' object has no attribute 'remove'
【解决方案2】:

我认为 '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

【讨论】:

    【解决方案3】:
    • 列出所有整数值(删除None)。
    • 然后对值进行排序并找到第 n 个最大值(即 n = 1 是最大值,n = 2 是第二大,等等)。
    • 提取与目标最大值对应的第一个键值。
    def f(input_dict, nth_largest_value):
        """Return nth largest value when sorting values in ascending order"""
        
        # get only unique integer values
        dict_values = list(set([x for x in input_dict.values() if type(x) == int])) 
        dict_values = sorted(dict_values) # ascending order
        if len(dict_values) >= nth_largest_value:
            for key in input_dict:
                if input_dict[key] == dict_values[-nth_largest_value]:
                    return key
    

    输入:f({'a': None, 'b': None, 'c': 400, 'd': 500}, 2)

    输出:'c'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-09
      • 1970-01-01
      • 2021-05-10
      • 1970-01-01
      • 2014-03-22
      • 2021-05-20
      • 2018-05-11
      相关资源
      最近更新 更多