1

重複の可能性:
逆辞書検索 - Python

Python で値によって辞書にインデックスを付ける組み込みの方法はありますか。

例:

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]

または手動でループする必要がありますか?

4

3 に答える 3

5

リスト内包表記を使用できます:

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)]
于 2012-04-04T16:44:05.750 に答える
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'
于 2012-04-04T16:43:34.730 に答える
3

要件は、思っているよりも複雑です。

  • リスト値とプレーン値の両方を処理する必要があります
  • 実際にキーを取得する必要はありませんが、キーのリストを取得します

これは、次の 2 つの手順で解決できます。

  1. すべての値がリストになるように dict を正規化します (すべてのプレーンな値は単一の要素になります)
  2. 逆引き辞書を作る

次の関数はこれを解決します。

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']}

したがって、逆引き辞書を一度作成してから、値で検索してキーのリストを取得するだけです。

于 2012-04-04T16:50:25.340 に答える