0
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?

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 5
    There's no bulit-in way, you need to write a loop over `dict.items()`. BTW, you shouldn't use `dict` as a variable name, since it's the name of the type. – Barmar Mar 15 '20 at 03:30
  • Welcome to stackoverflow! Based on the question, I have to wonder if a dictionary is the right data structure for what you're trying to do. Could you provide more context so we can find out? – kojiro Mar 15 '20 at 03:49
  • Or perhaps this? [Reverse / invert a dictionary mapping](https://stackoverflow.com/q/483666/418413) – kojiro Mar 15 '20 at 03:51

6 Answers6

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)
BruceWayne
  • 22,923
  • 15
  • 65
  • 110
0

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)
João Victor
  • 407
  • 2
  • 10
0

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}")
0

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)

0
my_dict = {"Hi":1, "Bye":2, "Hello":1, "Good-bye":6}
for key, value in my_dict.items() :
    if value == 1 :
        print (key, value)
Supertech
  • 746
  • 1
  • 9
  • 25
0

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