是否可以在某个数字下查找字典值的键?
例如,我有这样的字典:
sampleDict = {0: 0, 1: 10, 2: 2, 3: 3, 4: 4}
我知道我可以使用get()
函数获取特定键的值,但是有没有办法以条件方式进行相反的方法?
例如,如果我想在sampledict
中获取最大数字的密钥怎么办。我可以使用良好的功能或一组功能来快速有效地获得该值吗?我尝试了快速的Google搜索,但是我没有想出我想要的。在此示例中,我想接收数字1
,因为键1
的值是字典中的最大值。
For example, I have a dictionary like such:
sampleDict = {0: 0, 1: 10, 2: 2, 3: 3, 4: 4}
I know that I can use the get()
function to get the value of a particular key, but is there a way to do the opposite in a conditional manner?
For example, what if I wanted to get the key for maximum number in sampleDict
. Is there a good function or set of functions I can use to quickly and efficiently get that value? I've tried a quick Google search, but I'm not coming up with what I want. In this example, I would want to receive the number 1
since the value for key 1
is the maximum value in the dictionary.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要获得最大值,您可以使用
max()
内置函数:打印:
To get with max value you can use
max()
builtin function:Prints:
此返回具有您搜索值的键。
This return a array of keys that have the value you search.
您可以使用循环查找与最大值相匹配的密钥:
结果:
1
这显然不会解释任何DUPE最大值。它只是找到与最大值匹配的第一个值。
在性能方面,假设输入大小并不大。
如果我们需要提高效率,我们可以在迭代时计算最大值。
You can use a loop to find the key which matches the max value:
Result:
1
This obviously does not account for any dupe max values. It just finds the first value that matches the max.
In terms of performance, this assumes the input size is not massive.
If we needed to make it more efficient, we could calculate the maximum as we iterate.