Reputation: 99
I want to obtain output like
{'episodes': [{'season': 1, 'plays': 0, 'episode': 11}, {'season': 2, 'plays': 0, 'episode': 1}], 'title': 'SHOWNAME1', 'imdb_id': 'tt1855924'}
{'episodes': [{'season': 4, 'plays': 0, 'episode': 11}, {'season': 5, 'plays': 0, 'episode': 4}], 'title': 'SHOWNAME2', 'imdb_id': 'tt1855923'}
{'episodes': [{'season': 6, 'plays': 0, 'episode': 11}, {'season': 6, 'plays': 0, 'episode': 12}], 'title': 'SHOWNAME3', 'imdb_id': 'tt1855922'}
but I am stuck on the append line as I need to append to a value inside the dictionary. If title is not in the dictionary it creates the first entry for that title
{'episodes': [{'season': 1, 'plays': 0, 'episode': 12}], 'title': 'Third Reich: The Rise & Fall', 'imdb_id': 'tt1855924'}
Then if the same title appears again I want season, episode and plays to be inserted into the existing line. The script would then do the next show and either create a new entry or append again if there is already en entry for that title.... and so on
if 'title' in show and title in show['title']:
ep = {'episode': episode, 'season': season}
ep['plays'] = played
?????????????????????.append(ep)
else:
if imdb_id:
if imdb_id.startswith('tt'):
show['imdb_id'] = imdb_id
if thetvdb != "0":
show['tvdb_id'] = thetvdb
if title:
show['title'] = title
ep = {'episode': episode, 'season': season}
ep['plays'] = played
show['episodes'].append(ep)
Thanks Martijn Pieters, I now have this
if title not in shows:
show = shows[title] = {'episodes': []} # new show dictionary
else:
show = shows[title]
if 'title' in show and title in show['title']:
ep = {'episode': episode, 'season': season}
ep['plays'] = played
show['episodes'].append(ep)
else:
This give me the output I wanted but just wanted to make sure it looked correct
Upvotes: 2
Views: 1479
Reputation: 1121942
You need to store your matches in a dictionary instead, keyed by title. You can then find the same show again if you encounter it in your file more than once:
shows = {}
# some loop producing entries
if title not in shows:
show = shows[title] = {'episodes': []} # new show dictionary
else:
show = shows[title]
# now you have `show` dictionary to work with
# add episodes directly to `show['episodes']`
After collecting all your shows, use shows.values()
to extract all show dictionaries as a list.
Upvotes: 1