Stack Overflow Asked by Ossz on December 3, 2020
So I have a list of movies containing information on name, imdb rating and category as follows:
movies = [
{
"name": "Usual Suspects",
"imdb": 7.0,
"category": "Thriller"
},
{
"name": "Hitman",
"imdb": 6.3,
"category": "Action"
},
I’m trying to create a function to search in each item of the list for the number decimal i.e. the imdb rating, to compare it to a threshold value (>5.5)
The method I was thinking was to search for each item in this list when the number occurs and returning this value as I go through this list.
If I wanted to go about this method how should I tackle it? I’ve been looking at ways to return a value from lists but the methods I’m finding are for already known items returning an index…
Thanks for any help/ advice!
Each position in your list are a dictionary, to acess the 'imdb' you need to do this:
# For each movie in the movies list
for movie in movies:
# 'imdb' is a key of your dictionary
if movie['imdb'] > 5.5: # The movie['imdb'] returns the value (the decimal number)
return True # You can add to another data structure to store for example
Correct answer by Juliano on December 3, 2020
movies = [
{
"name": "Usual Suspects",
"imdb": 7.0,
"category": "Thriller"
},
{
"name": "Hitman",
"imdb": 6.3,
"category": "Action"
}]
print([x['name'] for x in movies if x['imdb']>5.5])
Answered by Janith on December 3, 2020
Since movies
is a list of dictionaries, you could just loop through it if you don't have a massive dataset.
ls = []
for movie in movies:
if movie['imdb'] > 5.5:
ls.append(movie)
Answered by Jeff on December 3, 2020
for movie in movies:
imdb_score = movie['imdb']
if imdb_score > 5.5:
print(imdb_score)
Would this work for what you are trying to do?
Answered by yibo on December 3, 2020
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP