如何从字典中获得第二大值的第一个键?



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

谢谢!

我不认为'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
  • 列出所有整数值(除去None)
  • 然后排序,找到第n个最大值(即n = 1是最大值,n = 2)是第二大的等等)。
  • 提取目标max对应的第一个键值
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'

如果最大值重复呢?

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

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

相关内容

  • 没有找到相关文章

最新更新