Python Forum
Accessing values in list of dictionaries
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Accessing values in list of dictionaries
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

import requests
import locale

search = tmdb.Search()
response ="Enter a movie name: ")))
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']) + " " + "" + s['poster_path'] + " ")
    inc += 1
    if inc > 5:

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))
        print("It failed.")

#print(list1) prints the expected list of ids
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).
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*

Possibly Related Threads…
Thread Author Replies Views Last Post
  How to pass list of values to a API request URL chetansaip99 0 472 Sep-28-2021, 07:37 AM
Last Post: chetansaip99
  function that returns a list of dictionaries nostradamus64 2 536 May-06-2021, 09:58 PM
Last Post: nostradamus64
  Python dictionary with values as list to CSV Sritej26 4 910 Mar-27-2021, 05:53 PM
Last Post: Sritej26
  convert List with dictionaries to a single dictionary iamaghost 3 942 Jan-22-2021, 03:56 PM
Last Post: iamaghost
  How to discard list repeat values akanowhere 7 1,134 Dec-28-2020, 09:14 PM
Last Post: akanowhere
  List index out of range error while accessing 2 lists in python K11 2 799 Sep-29-2020, 05:24 AM
Last Post: K11
  Creating a list of dictionaries while iterating pythonnewbie138 6 1,329 Sep-27-2020, 08:23 PM
Last Post: pythonnewbie138
  Help accessing elements of list of dictionaries Milfredo 6 1,133 Sep-07-2020, 01:32 AM
Last Post: Milfredo
  Trouble with converting list , dict to int values! faryad13 7 1,474 Sep-04-2020, 06:25 AM
Last Post: faryad13
  How to make a list of values from a dictionary list? faryad13 2 798 Sep-03-2020, 03:45 PM
Last Post: faryad13

Forum Jump:

User Panel Messages

Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020