Evert Freeman
Evert Freeman

Reputation: 15

Using user input to search through a dictionary of various data-types?

I'm trying to take user input and check if it is in a dictionary. The user is expected to input strings, floats and ints but only strings are comparing properly.

searching for '5' returns works but neither 10 nor 15.0 do as the input is being converted to a string.

other than implementing a check to see force the user to nominate what type of data they are searching for is there a way to do this?

new_dict = {'a': '5', 'b':10, 'c':15.0}
do_something = False
search_term = input('enter term: ')
print(search_term)
print(type(search_term))
for k,v in new_dict.items():
    print(v)
    if v == search_term:
        do_something = True
        print ('yes')

print(do_something)

Thanks in advance!!

Upvotes: 1

Views: 73

Answers (3)

Ruan
Ruan

Reputation: 229

Replacing if v == search_term: with if repr(v) == search_term: works, it will work on '5' as the input, but not on "5" as the input.

Upvotes: 0

ncica
ncica

Reputation: 7206

just convert both variables that you are comparing into string:

new_dict = {'a': '5', 'b':10, 'c':15.0}
do_something = False
search_term = input('enter term: ')
for k,v in new_dict.items():
    if str(v) == str(search_term):
        do_something = True
        print ('yes')

print(do_something)

another solution:

new_dict = {'a': '5', 'b':10, 'c':15.0}
do_something = False
search_term = input('enter term: ')
for k,v in new_dict.items():
    try:
        search_term = float(search_term)
        v = float(v)
    except:
        pass
    if v == search_term:
        do_something = True
        print ('yes')

print(do_something)

Upvotes: 2

LinPy
LinPy

Reputation: 18578

you can do somthing like :

new_dict = {'a': '5', 'b':10, 'c':15.0}
do_something = False
search_term = input('enter term: ')
for k,v in new_dict.items():
    if v == int(search_term):
        do_something = True
        print("yes")
    elif v == str(search_term):
        do_something = True
        print ('yes')

Upvotes: 2

Related Questions