dict = {"Hi":1, "Bye":2, "Hello":1, "Good-bye":6"}
If I target a certain value, say, 1, how do I print the keys that goes along with the value of 1?
dict = {"Hi":1, "Bye":2, "Hello":1, "Good-bye":6"}
If I target a certain value, say, 1, how do I print the keys that goes along with the value of 1?
This will check all values and add their keys to a unique list:
def find_key(target, my_dict):
results = []
for ky, val in my_dict.items():
if str(val) == str(target) and ky not in results:
results.append(ky)
return results
my_dict = {"Hi": 1, "Bye": 2, "Hello": 1, "Good-bye": 6}
my_results = find_key("1", my_dict)
print(my_results)
There is no direct way to do this. Dict is for getting values by keys.
One way to do what you want is verifying one by one:
for key, value in dict.items():
if value == desired_value:
print(key)
Dictionaries were not intended to be used this way... but a solution could be.
py_dict = {"Hi":1, "Bye":2, "Hello":1, "Good-bye":6}
for key, value in py_dict.items():
if value == 6:
print(f"{key} holds the value {value}")
As suggested by @barmer walk through the dictionary using a for loop like duct.items() like so. Hope this helps
For key, value in d.items(): If value == 1: Print( key)
my_dict = {"Hi":1, "Bye":2, "Hello":1, "Good-bye":6}
for key, value in my_dict.items() :
if value == 1 :
print (key, value)
the beauty of python is that you can make a quick function if the one you are looking for is not avail
some_dict = {"a":1, "b":2}
f_value = 2
a = [key for key, value in some_dict if value == f_value]
i think this is the shortest we can go