-1

I was wondering, is there a way i can get a key by knowing its value? For example a code so you can just add the part with finding a key by its value.

ww = "the quick brown fox jumps over the lazy dog."
counts = dict()
words = ww.split()
val = []
for word in words:
    if word in counts:
        counts[word] += 1
    else:
        counts[word] = 1


for keys, values in counts.items():
    val.append(int(values))

here is the code the adds the word and how many times can we meet it in the code.

1 Answers1

2

You could make a function for this:

def get_key_by_value(dictionary, value):
    for k, v in dictionary.items():
        if v == value:
            return k
    return None

test_dict = {"one": "two", "two": "three"}
print(get_key_by_value("two")) # "one"

Note: This function only returns the first value - and since this is an unordered dict, it might specify any key with the value given. To fix this, you could add all the results to a list:

def get_keys_by_value(dictionary, value):
    result = []
    for k, v in dictionary.items():
        if v == value:
            result.append(k)
    return result

test_dict = {"one": "two", "two": "three"}
print(get_keys_by_value("two")) # ["one"]
Ayush Garg
  • 2,234
  • 2
  • 12
  • 28