Home > other >  Need help in appending dictionary items in python
Need help in appending dictionary items in python

Time:07-14

I am trying to get movies by genres from tmdb movie dataset by converting it into json.

There should be multiple entries for a specific genre like 'adventure', but all i get to see is the last record and seems like the previous records are getting overwritten. I have verified this by adding a print statement in the if statement and the details are showing up in the console but somehow getting overwritten.

Any help would be appreciated. Thanks!!

final_list = []
for i in range(1,1000):
        if genre_name in data[str(i)]['genres']:
            movie_dict["Title"] = data[str(i)]['title']
            movie_dict["Language"] = data[str(i)]['original_language']
            final_list = [movie_dict]
    return final_list

CodePudding user response:

try using final_list.append(movie_dict)

CodePudding user response:

Bro you were actually actually returning the list after each value was added try this way and it will not overwrite it. The main reason is that you were returning the list in the for loop and everytime the loop run it save new dictionary in the list and remove the old one

final_list = []
for i in range(1,1000):
        if genre_name in data[str(i)]['genres']:
            movie_dict["Title"] = data[str(i)]['title']
            movie_dict["Language"] = data[str(i)]['original_language']
            final_list.append(movie_dict)
return final_list
  • Related