Heim > Artikel > Backend-Entwicklung > Wie finde ich einen Schlüssel in einem Python-Wörterbuch anhand seines Werts?
Inverse Dictionary Lookup in Python
Finding a key in a dictionary by knowing its corresponding value can be challenging. A simple solution might involve iterating over the dictionary's items and searching for a matching value, but this can be inefficient especially for large dictionaries.
One improved approach is to use a generator expression:
<code class="python">key = next(key for key, value in dd.items() if value == 'value')</code>
This generator expression will only iterate as far as necessary to return the first matching key, significantly improving performance for large dictionaries. If no matching key is found, it will raise a StopIteration error. To handle this case and provide a more informative exception, consider catching the error and raising a ValueError or KeyError instead.
Das obige ist der detaillierte Inhalt vonWie finde ich einen Schlüssel in einem Python-Wörterbuch anhand seines Werts?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!