简体   繁体   中英

Python Dictionary error list indices must be integers or slices, not str

I have a dictionary below, but trying to get a list of movies with IMDB score greater than 5, but keep getting the error ' list indices must be integers or slices, not str'

movies = [{

"name": "Usual Suspects", 
"imdb": 7.0,
"category": "Thriller"
},
{
"name": "Hitman",
"imdb": 6.3,
"category": "Action"
},
{
"name": "Dark Knight",
"imdb": 9.0,
"category": "Adventure"
},
{
"name": "The Help",
"imdb": 8.0,
"category": "Drama"
}]

Any help would be appreciated

Classic way:

# lst = []
for movie in movies:
    if movie['imdb'] > 5:
        print (movie['name'])
        # lst.append(movie['name'])

Output:

Usual Suspects
Hitman
Dark Knight
The Help

With list comprehension:

print ([ movie['name'] for movie in movies if movie['imdb'] > 5 ])

Output:

['Usual Suspects', 'Hitman', 'Dark Knight', 'The Help']

You have a list of dictionaries..Try the following code

movies_with_good_rating = []
for movie in movies:
    if int(movie.get('imdb')) > 5:
       movies_with_good_rating.apppend(movie.get('name'))
print(movies_with_good_rating)

You have a list of dicts. Output needed is list of movies with Imdb greater than 5. Try the below code.

    movies_list = []
    for dictionary in movies :
        if dictionary["imdb"] > 5:
            movies_list.append(dictionary["name"])
    print(movies_list)

Output:

    ['Usual Suspects', 'Hitman', 'Dark Knight', 'The Help']

This is classic


for i in range(0,len(movies)) :
    if movies[i]["imdb"] > 5:
        print (movies[i]['name'])
     

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM