Heim  >  Artikel  >  Backend-Entwicklung  >  Wie finde ich einen Schlüssel in einem Python-Wörterbuch anhand seines Werts?

Wie finde ich einen Schlüssel in einem Python-Wörterbuch anhand seines Werts?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-17 15:57:02972Durchsuche

How to Find a Key in a Python Dictionary by Its Value?

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!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn