mo_shun
mo_shun

Reputation: 315

Force case on dictionary to compare user input in Python

I'm making a user input decision tree and I want to force the dictionary that the input is being compared to into lowercase. I've placed .lower() at various points and keep getting errors.

not_found = True
while True:
    if OPTIONS == "1" or 'a':
        ARTIST_PICK = str(raw_input(
            "Please pick an artist\n"
            "Or Q to quit: ")).lower
        print ARTIST_PICK

        **entries = allData(filename).data_to_dict()
        for d in entries:
            arts = d['artist']**

        if ARTIST_PICK in arts:
            print "found it"

        elif ARTIST_PICK == 'q':
            break

        else:
            print "Sorry, that artist could not be found. Choose again."
            not_found = False

This is a sample of the "entries" I'm trying to make lower and compare the user input to:

[{'album': 'Nikki Nack', 'song': 'Find a New Way', 'datetime': '2014-12-03 09:08:00', 'artist': 'tUnE-yArDs'},]

Upvotes: 0

Views: 86

Answers (2)

gcarvelli
gcarvelli

Reputation: 1580

If your problem was just comparing the artist names, then you could use list comprehension to make everything lowercase.

entries = allData(filename).data_to_dict()

if ARTIST_PICK in [ d['artist'].lower() for d in entries ]:
    print("found it")
elif ARTIST_PICK == "q":
    break
else
    print("Sorry, that artist could not be found. Choose again.")

Or if you'd rather use a for loop (rearranged a little for readability):

if(ARTIST_PICK != 'q'):
    entries = allData(filename).data_to_dict()

    found = False

    for d in entries:
        if ARTIST_PICK == d['artist'].lower():
            found = True
            break
        elif ARTIST_PICK == "q":
            break

    if(found):
        print("found it")
    else:
        print("Sorry, that artist could not be found. Choose again.")
else:
    # handle the case where the input is 'q' here if you want

By the way, as a matter of principle you should name your boolean variables as though you were using them in a sentence. Instead of setting a variable not_found to False if the variable isn't found, set a variable named found to False or set not_found to True. Makes things easier in the long run.

Upvotes: 1

Dwight J. Browne
Dwight J. Browne

Reputation: 378

ARTIST_PICK = str(raw_input( "Please pick an artist\n" "Or Q to quit: ")).lower()

Upvotes: 0

Related Questions