在字典中按值返回键 [英] return key by value in dictionary

查看:280
本文介绍了在字典中按值返回键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这种情况下,如果'b'在字典中,我想要将字符串中的键返回给一个值

I am trying to return the key in a dictionary given a value

,我希望它返回键在哪个'b'是(即2)

in this case if 'b' is in the dictionary, I want it to return the key at which 'b' is (i.e 2)

def find_key(input_dict, value):
    if value in input_dict.values():
        return UNKNOWN            #This is a placeholder
    else:
        return "None"

print(find_key({1:'a', 2:'b', 3:'c', 4:'d'}, 'b'))

我想得到的答案是关键2,但我不确定为了得到答案,任何帮助将不胜感激

The answer I want to get is the key 2, but I am unsure what to put in order to get the answer, any help would be much appreciated

推荐答案

返回首先匹配键:

Return first matching key:

def find_key(input_dict, value):
    return next((k for k, v in input_dict.items() if v == value), None)

返回所有匹配键作为一组:

def find_key(input_dict, value):
    return {k for k, v in input_dict.items() if v == value}

字典中的值不一定是唯一的。如果没有匹配,第一个选项返回 None ,第二个选项返回一个空集合。

Values in a dictionary are not necessarily unique. The first option returns None if there is no match, the second returns an empty set for that case.

由于字典的顺序是任意的(取决于使用什么键和插入和删除历史),被认为是第一个键也是任意的。

Since the order of dictionaries is arbitrary (dependent on what keys were used and the insertion and deletion history), what is considered the 'first' key is arbitrary too.

演示:

>>> def find_key(input_dict, value):
...     return next((k for k, v in input_dict.items() if v == value), None)
... 
>>> find_key({1:'a', 2:'b', 3:'c', 4:'d'}, 'b')
2
>>> find_key({1:'a', 2:'b', 3:'c', 4:'d'}, 'z') is None
True
>>> def find_key(input_dict, value):
...     return {k for k, v in input_dict.items() if v == value}
... 
>>> find_key({1:'a', 2:'b', 3:'c', 4:'d'}, 'b')
set([2])
>>> find_key({1:'a', 2:'b', 3:'c', 4:'d', 5:'b'}, 'b')
set([2, 5])
>>> find_key({1:'a', 2:'b', 3:'c', 4:'d'}, 'z')
set([])

请注意,每当我们需要搜索匹配的键时,我们需要循环使用这些值。这不是最有效的方法,特别是如果您需要经常匹配键值。在这种情况下,创建一个反向索引:

Note that we need to loop over the values each time we need to search for matching keys. This is not the most efficient way to go about this, especially if you need to match values to keys often. In that case, create a reverse index:

from collections import defaultdict

values_to_keys = defaultdict(set)

for key, value in input_dict:
    values_to_keys[value].add(key)

现在您可以直接在O(1)(常数)时间内询问一组密钥:

Now you can ask for the set of keys directly in O(1) (constant) time:

keys = values_to_keys.get(value)

这使用集合;字典没有任何订单,所以在这里,集合有点更有意义。

This uses sets; the dictionary has no ordering so either, sets make a little more sense here.

这篇关于在字典中按值返回键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆