I'm very new, and I'm working on a project that right now involves writing a function that will search for a dictionary contained in a list which is itself the value of one of two key/value pairs in another dictionary. The goal is to search for a movie by title, and then remove that movie's dict from that list and put it in a different list. Right now I've got
def watch_movie(user_data, title):
if title in user_data:
user_data["watchlist"].remove(title)
user_data["watched"].append(title)
return user_data
else:
return user_data
Any tips?
CodePudding user response:
I would use a for
loop to compare the title
of each dict to the input:
def watch_movie(user_data, title):
for d in user_data['watchlist']:
if d['title'] == title:
user_data["watchlist"].remove(d)
user_data["watched"].append(d)
break # assuming no two movies share the same title
return user_data
user_data = {"watchlist": [{"title": "Title A", "genre": "Fantasy", "rating": 4.8}], "watched": []}
user_data = watch_movie(user_data, 'Title A')
print(user_data) # {'watchlist': [], 'watched': [{'title': 'Title A', 'genre': 'Fantasy', 'rating': 4.8}]}