E.Arrowood
E.Arrowood

Reputation: 770

Python 3.4 Matching a string with a list of strings (in the form of keys from a dictionary) **ignoring case.**

The scenario: I have a dictionary of items:

d = {'abcde': 1, 'ETHAN': 2, 'dogsAndcats': 3, 'cat and MOUSE': 4}

I ask the user to input one of the four key values of the dictionary d:

user_input = input()

Then I take their value and check it against each key name in the dictionary:

for key in d.keys():
    if user_input == key:
        return True

Lets assume the user is being somewhat friendly and is at least entering the correct spelling of the words. But! -This is the whole basis of my question- the user neglects to use the correct capitalization.

How can I check the user's input against my list ignoring the capitalization?

I tried using regular expression methods .search and .match. See the code below:

def check_value_in_dict(val, d): 
    for k in d.keys():
        if re.search(val, k, re.IGNORECASE):
            return True

This returns true if the user only enters one correct letter in the string. It does not check the entire string which is necessary for my program.

Upvotes: 1

Views: 52

Answers (1)

coffee-converter
coffee-converter

Reputation: 977

Simply do:

if user_input.lower() == key.lower()

Upvotes: 1

Related Questions