从Python字典中的值查找键:

发布于 2024-12-08 09:29:57 字数 166 浏览 3 评论 0原文

对 Python 相当陌生,仍然在处理如此多的信息。

我见过的有关字典的所有文档都解释了通过键获取值的各种方法 - 但我正在寻找一种Python式的方法来执行相反的操作 - 通过值获取键。

我知道我可以循环遍历键并检查它们的值,直到找到我正在寻找的值,然后获取键,但我正在寻找直接路径。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(4

ぃ双果 2024-12-15 09:29:57

没有直达路线。不过,使用列表推导式就很容易了;

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

如果您偶尔需要这样做,并且认为以其他方式对其进行索引也不值得,您可以执行以下操作:

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]

然后 d.key_with_value 的行为将类似于 d.get,除非反过来。

您还可以创建一个自动为其双向建立索引的类。那么键和值都需要是可散列的。以下是它的三种实现方式:

  • 在两个单独的字典中,公开一些类似字典的方法;你也许可以这样做 foo.by_key[key]foo.by_value[value]。 (没有给出代码,因为它更复杂,而且我很懒,而且我认为这无论如何都是次优的。)

  • 在不同的结构中,这样你就可以做 d[key]d.inverse[值]

    类 bidict(dict):
        def __init__(self, *args, **kwargs):
            self.inverse = {}
            super(bidict, self).__init__(键, 值)
    
        def __setitem__(自身,键,值):
            超级(bidict,自我).__setitem__(键,值)
            self.inverse[值] = 键
    
        def __delitem__(self, key):
            del self.inverse[self[key]]
            super(bidict, self).__delitem__(key)
    
  • 在相同的结构中结构,以便您可以执行 d[key]d[value]

    类 bidict(dict):
        def __setitem__(自身,键,值):
            超级(bidict,自我).__setitem__(键,值)
            super(bidict, self).__setitem__(值, 键)
    
        def __delitem__(self, key):
            super(bidict, self).__delitem__(self[key])
            super(bidict, self).__delitem__(key)
    

值得注意的是,这些实现中没有bidictupdate 方法,它会稍微复杂一些(但是 help(dict.update) 将指示您需要涵盖的内容)没有更新bidict({1:2}) 不会执行其预期的操作,d.update({1:2}) 也不会执行此操作。)

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

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.

她如夕阳 2024-12-15 09:29:57

由于您的字典可能包含重复值(即 {'a': 'A', 'b': 'A'}),因此从值中查找键的唯一方法是迭代字典正如你所描述的。

或者...建立相反的字典。每次修改原始词典后都必须重新创建它。

或者...编写一个维护双向字典的类。您将必须管理出现重复值的情况。

Since your dictionary can contain duplicate values (i.e. {'a': 'A', 'b': 'A'}), the only way to find a key from value is to iterate over the dictionary as you describe.

Or... build the opposite dictionary. you have to recreate it after each modification of the original dictionary.

Or... write a class that maintains both-ways dictionary. You will have to manage situations where duplicate value appears.

来世叙缘 2024-12-15 09:29:57

第一个具有列表理解的解决方案很好。
但针对 python 3.x 的一个小修复,应该是 .items(),而不是 .iteritems()

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

the first solution with the list comprehension is good.
but a small fix for python 3.x, instead of .iteritems() it should be just .items():

[k for k, v in d.items() if v == desired_value]
冰火雁神 2024-12-15 09:29:57

构建相反的字典根本不是一个好方法,因为一个或多个键具有相同的值,但如果将其反转,则需要插入 key:[value1,... ] 结构,这将导致另一个问题。

Building a opposite dictionary is not at all good manner as one or more key have same value but if you invert it you need to insert key:[value1,... ] structure which will lead you to another problem.

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