Accessing values in list of dictionaries - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Accessing values in list of dictionaries (/thread-28764.html) |
Accessing values in list of dictionaries - pythonnewbie138 - Aug-02-2020 I'm struggling with iterating over a list of dictionaries to access keys/values based on a user selection. The first loop works as expected to print the chosen dict values for a user to review but the second one attempting to match the user input to the dictionary key to access the 'id' value within it is not working. The script ends with it printing "It failed." Is this a data type conversion issue? What am I missing here? import tmdbsimple as tmdb tmdb.API_KEY = 'API KEY REMOVED FOR PUBLIC POSTING' import requests import locale search = tmdb.Search() response = search.movie(query=str(input("Enter a movie name: "))) #print(response) list1 = [] inc = 1 #generate list for user to review for s in search.results: print(str(inc) + "." + s['title'] + " " + s['release_date'] + " " + str(s['id']) + " " + "https://image.tmdb.org/t/p/original" + s['poster_path'] + " ") list1.append(s['id']) inc += 1 if inc > 5: break enumerate(list1, 1) choice = input("Choose a movie: ") choice1 = list1[int(choice)-1] #iterate over list of dictionaries again to match user choice to correct dict for t in search.results: if t['id'] == choice1: print("You chose " + str(choice1)) else: print("It failed.") break #print(list1) prints the expected list of ids RE: Accessing values in list of dictionaries - deanhystad - Aug-02-2020 Only use dictionary[key] if you know the key exists, if you have code in place to catch the KeyError exception, or if it is ok for the call to raise an exception. Take a look at dictionary.get(key). RE: Accessing values in list of dictionaries - pythonnewbie138 - Aug-02-2020 Ok I figured out what I did wrong. In testing, I was choosing #2 repeated but that triggered the else block and broke out of the loop before getting to the correct match. *newbie facepalm* |