'extracting subset of data from a list of dict based on keys

Here is my data structure - it's a list of dictionaries of movies information with keys like title, year, genre.

Here's just a small sample.

{'Action': [{'title': 'They Live',
   'year': 1988,
   'genres': ['Action', 'Horror', 'Sci-Fi'],
   'duration': 94,
   'directors': ['John Carpenter'],
   'actors': ['Roddy Piper', 'Keith David', 'Meg Foster'],
   'rating': 7.3},
  {'title': 'Ultra Warrior',
   'year': 1990,
   'genres': ['Action', 'Adventure', 'Sci-Fi'],
   'duration': 81,
   'directors': ['Augusto Tamayo San Román', 'Kevin Tent'],
   'actors': ['Dack Rambo',
    'Clare Beresford',
    'Meshach Taylor',
    'Mark Bringelson'],
   'rating': 1.9},
  {'title': 'Kick-Ass 2',
   'year': 2013,
   'genres': ['Action', 'Comedy', 'Crime'],
   'duration': 103,
   'directors': ['Jeff Wadlow'],
   'actors': ['Aaron Taylor-Johnson', 'Chloë Grace Moretz'],
   'rating': 6.5},.... 
'Drama': [{'title': 'Dirty Beautiful',
   'year': 2015,
   'genres': ['Comedy', 'Drama', 'Romance'],
   'duration': 95,
   'directors': ['Tim Bartell'],
   'actors': ['Ricky Mabe', 'Jordan Monaghan', 'Conor Leslie', 'Darin Heames'],
   'rating': 5.5},
  {'title': 'Honeydripper',
   'year': 2007,
   'genres': ['Crime', 'Drama', 'History', 'Action', 'Adventure'],
   'duration': 124,
   'directors': ['John Sayles', 'Wachowskis'],
   'actors': ['Danny Glover', 'LisaGay Hamilton', 'Yaya DaCosta'],
   'rating': 6.6}, } 

Based on info about directors (from key: directors) I need to pull a subset of data. The question is - what are the titles of the movies directed by the Wachowskis that contain both 'Action' and 'Adventure' in their genre? The output should be a list.

Thank you so much for any help!!



Solution 1:[1]

You could try a list comprehension:

action_adventure_wachowskis_movies = [
   movie['title']
   for genre in data
   for movie in data[genre]
   if 'Wachowskis' in movie['directors'] and
      {'Action', 'Adventure'}.issubset(movie['genres'])
]
print(action_adventure_wachowskis_movies)

Output:

['Honeydripper']

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sash Sinha