Most efficient method to get key for a value in a dict

后端 未结 4 1030
天涯浪人
天涯浪人 2020-12-18 15:07

I have a dictionary of objects:

dic = {\'k1\':obj1, \'k2\':obj2, \'k3\':obj3, ...}

class MyObject:
    def __init__(self,x,y):
        self.x=x
        self         


        
相关标签:
4条回答
  • 2020-12-18 15:41

    Ignoring the possibility that samb8s raises, that multiple keys exist for a single value, you can easily reverse the dictionary like this:

    reverse_dic = dict((v, k) for k, v in dic.items())
    
    0 讨论(0)
  • 2020-12-18 15:49

    This will return a set of ALL keys that have that value - like a filter by value:

    def find_keys(dic, val):
        return set(k for k,v in dic.items() if v == val)
    
    0 讨论(0)
  • 2020-12-18 15:54

    regular dict[key] -> value

    my_regular_dict = {1: 2, 3: 4, 5: 6}
    

    reverse lookup, dict[value] -> key

    my_reverse_lookup = dict([(val, key) for key, val in my_regular_dict.items()])
    
    0 讨论(0)
  • 2020-12-18 15:58

    You can use list comprehension. This code gives you the keys in a list:

    >>> a
    {1: 2, 3: 4, 9: 4, 5: 6, 7: 8}
    >>> [key for key, value in a.items() if value == 4]
    [3, 9]
    
    0 讨论(0)
提交回复
热议问题