Created
August 31, 2021 19:02
-
-
Save alvinwan/35c679e5702e43c53be92fa6700a4bbf to your computer and use it in GitHub Desktop.
Get key by Python dictionary value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>>> list_to_dict=[{"a":1},{"b":2}] | |
>>> for key, value in list_to_dict.items(): | |
... if value == 1: | |
... break | |
... | |
>>> key | |
'a' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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