索引python字典的值

Fer*_*uzz 1 python dictionary

可能重复:
反向字典查找 - Python

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

例如:

dict = {'fruit':'apple','colour':'blue','meat':'beef'}
print key where dict[key] == 'apple'
Run Code Online (Sandbox Code Playgroud)

要么:

dict = {'fruit':['apple', 'banana'], 'colour':'blue'}
print key where 'apple' in dict[key]
Run Code Online (Sandbox Code Playgroud)

或者我必须手动循环吗?

Wil*_*uck 5

你可以使用列表理解:

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

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

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

列表理解是通过字典items方法给出的所有键值对,并创建值为"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
Run Code Online (Sandbox Code Playgroud)

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

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