在Python字典中从值中查找键值: [英] Finding key from value in Python dictionary:

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

问题描述

相当新的Python,仍然在努力与这么多的信息。



我看过的关于词典的所有文档都解释了通过键获取值的各种方法 - 但是我正在寻找一种pythonic的方式来做相反的事情一个键值通过一个值。



我知道我可以通过键循环检查他们的值,直到找到我正在寻找的值,然后抓住钥匙,但是我正在寻找一条直线路线。

解决方案

没有直接路线。尽管如此,列表可以很容易的;

  [k for k,v in d.iteritems()if v == desired_value ] 

如果你需要偶尔这样做,不要以其他方式索引它是值得的你也可以这样做:

  class bidict(dict):
def key_with_value(self,value,默认=无):
for k,v in self.iteritems():
if v == value:
return v
return default

def keys_with_value(self,value,default = None):
return [v for k,v in self.iteritems()if v == value]

然后 d.key_with_value 将表现得像 d.get ,除了另一种方式。



您还可以自动创建一个自动对其进行索引的类。关键和价值都需要是可以哈希的。这里有三种可以实现的方法:




  • 在两个单独的段落中,暴露了一些类似于类似的方法;你可以做 foo.by_key [key] foo.by_value [value] 。 (没有代码给出,因为它更复杂,我很懒惰,我认为这也是次佳的。)


  • 在一个不同的结构,所以你可以做 d [key] d.inverse [value]




    $ _ code


    $ (bid,self).__ init __(key,value)

    def __setitem __(self,key,value):
    super(bidict,self).__ setitem __(key,value)
    self.inverse [value] = key

    def __delitem __(self,key):
    del self.inverse [self [key]]
    super(bidict,self)。 __delitem __(key)


  • 在同一个结构中,所以你可以做 d [key] d [value]

     
    def __setitem __(self,key,value):
    super(bidict,self).__ setitem __(key,value)
    super(bidict ,self)。setitem __(v

    def __delitem __(self,key):
    super(bidict,self).__ delitem __(self [key])
    super(bidict,self).__ delitem__ (key)




(在这些实现中,一个 bidict 更新方法,这将稍微复杂一些(但$ code> help .update)将显示您需要覆盖的内容。没有更新 bidict({1:2})不会做它的意图, code> d.update({1:2})。)



还要考虑一些其他数据结构是否更合适。


Fairly new to Python, still struggling with so much information.

All the documentation I've seen about dictionaries explain various ways of getting a value via a key - but I'm looking for a pythonic way to do the opposite - get a key via a value.

I know I can loop through the keys and inspect their values until I find the value I'm looking for and then grab the key, but I'm looking for a direct route.

解决方案

There is no direct route. It's pretty easy with list comprehensions, though;

[k for k, v in d.iteritems() if v == desired_value]

If you need to do this occasionally and don't think it's worth while indexing it the other way as well, you could do something like:

class bidict(dict):
    def key_with_value(self, value, default=None):
        for k, v in self.iteritems():
            if v == value:
                return v
        return default

    def keys_with_value(self, value, default=None):
        return [v for k, v in self.iteritems() if v == value]

Then d.key_with_value would behave rather like d.get, except the other way round.

You could also make a class which indexed it both ways automatically. Key and value would both need to be hashable, then. Here are three ways it could be implemented:

  • In two separate dicts, with the exposing some dict-like methods; you could perhaps do foo.by_key[key] or foo.by_value[value]. (No code given as it's more complicated and I'm lazy and I think this is suboptimal anyway.)

  • In a different structure, so that you could do d[key] and d.inverse[value]:

    class bidict(dict):
        def __init__(self, *args, **kwargs):
            self.inverse = {}
            super(bidict, self).__init__(key, value)
    
        def __setitem__(self, key, value):
            super(bidict, self).__setitem__(key, value)
            self.inverse[value] = key
    
        def __delitem__(self, key):
            del self.inverse[self[key]]
            super(bidict, self).__delitem__(key)
    

  • In the same structure, so that you could do d[key] and d[value]:

    class bidict(dict):
        def __setitem__(self, key, value):
            super(bidict, self).__setitem__(key, value)
            super(bidict, self).__setitem__(value, key)
    
        def __delitem__(self, key):
            super(bidict, self).__delitem__(self[key])
            super(bidict, self).__delitem__(key)
    

(Notably absent from these implementations of a bidict is the update method which will be slightly more complex (but help(dict.update) will indicate what you'd need to cover). Without update, bidict({1:2}) wouldn't do what it was intended to, nor would d.update({1:2}).)

Also consider whether some other data structure would be more appropriate.

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

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