リスト内包表記を使用できます:
my_dict = {'fruit':'apple','colour':'blue','meat':'beef'}
print [key for key, value in my_dict.items() if value == 'apple']
上記のコードは、あなたが望んでいることをほぼ正確に実行しています:
print key where dict[key] == 'apple'
items
リスト内包表記は、辞書のメソッドで指定されたすべてのキーと値のペアを調べ、値が「apple」であるすべてのキーの新しいリストを作成します。
Niklas が指摘したように、値がリストである可能性がある場合、これは機能しません。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)]