-1

Using the following route with Flask to pull from a MongoDB:

@app.route('/search-all/', methods=['GET', 'POST']) # EDIT
def search_all():
    for x in db['mongo-moviedb'].find({"Films.Title" : "Clue"}, {"Films.$": 1}):
        result = x
        return render_template('Date-Night.html', result=result)

Which returns the following:

{'Films': [{'Actors': 'Eileen Brennan, Tim Curry, Madeline Kahn',
            'Awards': 'N/A',
            'BoxOffice': '$14,643,997',
            'Country': 'United States',
            'DVD': '27 Jun 2000',
            'Director': 'Jonathan Lynn',
            'Genre': 'Comedy, Crime, Mystery',
            'Language': 'English, French',
            'Metascore': '39',
            'Plot': 'Six guests are anonymously invited to a strange mansion '
                    'for dinner, but after their host is killed, they must '
                    'cooperate with the staff to identify the murderer as the '
                    'bodies pile up.',
            'Poster': 'https://m.media-amazon.com/images/M/MV5BM2VlNTE1ZmMtOTAyNS00ODYwLWFmY2MtZWEzOTE2YjE1NDE2XkEyXkFqcGdeQXVyNDk3NzU2MTQ@._V1_SX300.jpg',
            'Production': 'N/A',
            'Rated': 'PG',
            'Ratings': [{'Source': 'Internet Movie Database',
                         'Value': '7.2/10'},
                        {'Source': 'Rotten Tomatoes', 'Value': '68%'},
                        {'Source': 'Metacritic', 'Value': '39/100'}],
            'Released': '13 Dec 1985',
            'Response': 'True',
            'Runtime': '94 min',
            'Title': 'Clue',
            'Type': 'movie',
            'Website': 'N/A',
            'Writer': 'John Landis, Jonathan Lynn, Anthony E. Pratt',
            'Year': '1985',
            'imdbID': 'tt0088930',
            'imdbRating': '7.2',
            'imdbVotes': '96,112'}],
 '_id': ObjectId('638135b01687bf075645b0da')}

What I can't figure out is how to access the nested Films list, to grab specific items (Title, Year etc.) and load those into individual variables (x, y, z).

I've tried x['Films'], x['Films.Title'], x['Films'],['Title'], but I'm not sure what I'm looking for here. Thanks, guys.

davidism
  • 121,510
  • 29
  • 395
  • 339
  • 2
    Does this answer your question? [Access nested dictionary items via a list of keys?](https://stackoverflow.com/questions/14692690/access-nested-dictionary-items-via-a-list-of-keys) – accdias Dec 25 '22 at 02:28

1 Answers1

1

x["Films"] is a list with just one value, so:

x["Films"][0]["Title"]
Jonathan Ciapetti
  • 1,261
  • 3
  • 11
  • 16
  • 1
    Brilliant! I was forgetting the reference to the secondary list's index. – Michael Jason Stokes Dec 25 '22 at 02:21
  • 1
    @MichaelJasonStokes also, about the other ways tried, in the case `Title` was an attribute of the object from `x['Films']`, `x['Films.Title']` would not access `Title`: it's not the valid syntax. Instead, in that case `x['Films'].Title` is needed. – Jonathan Ciapetti Dec 25 '22 at 02:25