Skip to content

Instantly share code, notes, and snippets.

@alvinwan
Created August 31, 2021 19:02
Show Gist options
  • Save alvinwan/35c679e5702e43c53be92fa6700a4bbf to your computer and use it in GitHub Desktop.
Save alvinwan/35c679e5702e43c53be92fa6700a4bbf to your computer and use it in GitHub Desktop.
Get key by Python dictionary value
>>> list_to_dict=[{"a":1},{"b":2}]
>>> for key, value in list_to_dict.items():
... if value == 1:
... break
...
>>> key
'a'
def keyof(dictionary, value):
"""Find key belonging to the provided value.
>>> veggie_to_cost = {'cabbage': 1, 'carrot': 2}
>>> keyof(veggie_to_cost, 1)
'cabbage'
"""
for key, candidate in dictionary.items():
if value == candidate:
return key
raise ValueError(f"Value {value} not found in dictionary")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment