# toy dataset
movies = [
{
'title': 'The Shawshank Redemption',
'description': 'Two imprisoned men bond over several years, finding solace and eventual redemption through acts of common decency.',
'genre': 'Drama'
},
{
'title': 'Inception',
'description': 'A thief who steals corporate secrets through the use of dream-sharing technology is given the inverse task of planting an idea into the mind of a CEO.',
'genre': 'Action, Adventure, Sci-Fi'
},
{
'title': 'Pulp Fiction',
'description': 'The lives of two mob hitmen, a boxer, a gangster and his wife, and a pair of diner bandits intertwine in four tales of violence and redemption.',
'genre': 'Crime, Drama'
},
{
'title': 'The Dark Knight',
'description': 'When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, Batman must accept one of the greatest psychological and physical tests of his ability to fight injustice.',
'genre': 'Action, Crime, Drama'
},
{
'title': 'The Matrix',
'description': 'A computer hacker learns from mysterious rebels about the true nature of his reality and his role in the war against its controllers.',
'genre': 'Action, Sci-Fi'
}
]
def get_description_length(movie_title):
for movie in movies:
if movie['title'] == movie_title:
return len(movie['description'])
return 0 # Return 0 if the movie title is not found in the dataset
print(get_description_length('The Matrix'))
如果数据是字典:
movies = {
'The Shawshank Redemption': {
'description': 'Two imprisoned men bond over several years, finding solace and eventual redemption through acts of common decency.',
'genre': 'Drama'
},
'Inception': {
'description': 'A thief who steals corporate secrets through the use of dream-sharing technology is given the inverse task of planting an idea into the mind of a CEO.',
'genre': 'Action, Adventure, Sci-Fi'
},
'Pulp Fiction': {
'description': 'The lives of two mob hitmen, a boxer, a gangster and his wife, and a pair of diner bandits intertwine in four tales of violence and redemption.',
'genre': 'Crime, Drama'
},
'The Dark Knight': {
'description': 'When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, Batman must accept one of the greatest psychological and physical tests of his ability to fight injustice.',
'genre': 'Action, Crime, Drama'
},
'The Matrix': {
'description': 'A computer hacker learns from mysterious rebels about the true nature of his reality and his role in the war against its controllers.',
'genre': 'Action, Sci-Fi'
}
}
那么这样的事情就会奏效:
def get_movie_description_length(dictionary_entry):
print(len(movies[dictionary_entry]['description']))
get_movie_description_length('The Matrix')