索引python字典的值

时间:2012-04-04 16:41:15

标签: python dictionary

  

可能重复:
  Inverse dictionary lookup - Python

是否有内置的方法可以在Python中按值索引字典。

e.g。类似的东西:

dict = {'fruit':'apple','colour':'blue','meat':'beef'}
print key where dict[key] == 'apple'

或:

dict = {'fruit':['apple', 'banana'], 'colour':'blue'}
print key where 'apple' in dict[key]

还是我必须手动循环呢?

3 个答案:

答案 0 :(得分:5)

您可以使用list comprehension

my_dict = {'fruit':'apple','colour':'blue','meat':'beef'}
print [key for key, value in my_dict.items() if value == 'apple']

上面的代码几乎完全符合您的要求:

  

打印键dict [key] =='apple'

列表理解是通过字典items method给出的所有键值对,并创建值为'apple'的所有键的新列表。

正如尼克拉斯指出的那样,当你的价值观可能成为名单时,这不起作用。在in之后,您必须小心谨慎使用'apple' in 'pineapple' == True。因此,坚持使用列表推导方法需要进行一些类型检查。因此,您可以使用辅助函数,如:

def equals_or_in(target, value):
    """Returns True if the target string equals the value string or,
    is in the value (if the value is not a string).
    """
    if isinstance(target, str):
        return target == value
    else:
        return target in value

然后,下面的列表理解将起作用:

my_dict = {'fruit':['apple', 'banana'], 'colour':'blue'}
print [key for key, value in my_dict.items() if equals_or_in('apple', value)]

答案 1 :(得分:4)

你必须手动循环它,但如果你需要重复查找,这是一个方便的技巧:

d1 = {'fruit':'apple','colour':'blue','meat':'beef'}

d1_rev = dict((v, k) for k, v in d1.items())

然后您可以像这样使用反向字典:

>>> d1_rev['blue']
'colour'
>>> d1_rev['beef']
'meat'

答案 2 :(得分:3)

您的要求比您意识到的要复杂得多:

  • 您需要同时处理列表值和普通值
  • 您实际上不需要取回钥匙,而是钥匙列表

您可以分两步解决这个问题:

  1. 规范化dict,使每个值都是一个列表(每个普通值变为单个元素)
  2. 构建反向字典
  3. 以下功能将解决此问题:

    from collections import defaultdict
    
    def normalize(d):
        return { k:(v if isinstance(v, list) else [v]) for k,v in d.items() }
    
    def build_reverse_dict(d):
        res = defaultdict(list)
        for k,values in normalize(d).items():
            for x in values:
                res[x].append(k)
        return dict(res)
    

    要像这样使用:

    >>> build_reverse_dict({'fruit':'apple','colour':'blue','meat':'beef'})
    {'blue': ['colour'], 'apple': ['fruit'], 'beef': ['meat']}
    >>> build_reverse_dict({'fruit':['apple', 'banana'], 'colour':'blue'})
    {'blue': ['colour'], 'apple': ['fruit'], 'banana': ['fruit']}
    >>> build_reverse_dict({'a':'duplicate', 'b':['duplicate']})
    {'duplicate': ['a', 'b']}
    

    因此,您只需构建一次反向字典,然后按值查找并返回一个键列表。