【发布时间】: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