Skip to content Skip to sidebar Skip to footer

Using A Users Input To Search Dictionary Keys And Print That Keys Matching Value

I am working with tkinter, as I have my gui set up with and entry, label, and button. I'm trying to search my dictionary's keys with the users' input from the entry, and print the

Solution 1:

Since it's a dictionary, you can directly use get() to get the value of the key.

def btn_Clicked():
    x = txt.get()
    check_in_dict = dict.get(x)

    if check_in_dict:
        decision.configure(text = "Your value, " + str(check_in_dict))
    else:
        decision.configure(text = "No key found")

Solution 2:

Use the get method, which returns None if the key isn't found.

v = d.get(x)
if x:
    decision.configure(text = f"Your value, {v}")
else:
    decision.configure(text = f"No key found for {x}")

Solution 3:

dictionary = {"AA":1, "BB":2, "CC":3}

Below code will go into the button pressed

key = input("the key") # key is assumed to be input here

try:
    value = dictionary[key] # user entered key

    # do what you want with key and its value
    decision.configure(text = "Your value, " + value)

# if key not found in dict it would raise KeyError
except KeyError:
    # key not found message goes here
    decision.configure(text = "No key found")

Post a Comment for "Using A Users Input To Search Dictionary Keys And Print That Keys Matching Value"