是否可以在某个数字下查找字典值的键?

发布于 2025-02-05 17:25:53 字数 322 浏览 1 评论 0原文

例如,我有这样的字典:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

洋洋洒洒 2025-02-12 17:25:54

要获得最大值,您可以使用max()内置函数:

sampleDict = {0: 0, 1: 10, 2: 2, 3: 3, 4: 4}

max_key = max(sampleDict, key=sampleDict.get)
print(max_key)

打印:

1

To get with max value you can use max() builtin function:

sampleDict = {0: 0, 1: 10, 2: 2, 3: 3, 4: 4}

max_key = max(sampleDict, key=sampleDict.get)
print(max_key)

Prints:

1
故人如初 2025-02-12 17:25:54

此返回具有您搜索值的键。

keys = [k for k, v in sampleDict.items() if v == value]
print(keys)

This return a array of keys that have the value you search.

keys = [k for k, v in sampleDict.items() if v == value]
print(keys)
酷炫老祖宗 2025-02-12 17:25:54

您可以使用循环查找与最大值相匹配的密钥:

sampleDict = {0: 0, 1: 10, 2: 2, 3: 3, 4: 4}

def foo(sampleDict):
    m = max(sampleDict.values())
    for k, v in sampleDict.items():
        if v == m:
            return k

print(foo(sampleDict))

结果1

这显然不会解释任何DUPE最大值。它只是找到与最大值匹配的第一个值。

在性能方面,假设输入大小并不大。

如果我们需要提高效率,我们可以在迭代时计算最大值。

You can use a loop to find the key which matches the max value:

sampleDict = {0: 0, 1: 10, 2: 2, 3: 3, 4: 4}

def foo(sampleDict):
    m = max(sampleDict.values())
    for k, v in sampleDict.items():
        if v == m:
            return k

print(foo(sampleDict))

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文