AnswerBun.com

Searching for an number in a list with strings, to return the number value

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!

4 Answers

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

Add your own answers!

Related Questions

How to convet this data to array?(Typescript )

1  Asked on December 23, 2021 by pyarel

   

Why is the user defined time’s location nil

1  Asked on December 23, 2021 by kelly-flet

 

Can i uncheck radio button?

3  Asked on December 23, 2021 by frankfurt

     

Call this.Hide() but the Form is still activated on Win10

0  Asked on December 23, 2021 by jonney

 

How do you remotely update Java applications?

9  Asked on December 23, 2021 by david-crow

   

how to embed plot in gtk and glade

1  Asked on December 23, 2021 by user169808

     

Multivariate normal density in Python?

10  Asked on December 23, 2021 by benno

       

onBlur for div element in React

1  Asked on December 23, 2021 by neel-dsouza

   

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir