python - Append to a list within a dictionary -


i want 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 stuck on append line need append value inside dictionary. if title not in dictionary creates first entry title

{'episodes': [{'season': 1, 'plays': 0, 'episode': 12}], 'title': 'third reich: rise & fall', 'imdb_id': 'tt1855924'} 

then if same title appears again want season, episode , plays inserted existing line. script next show , either create new entry or append again if there en entry title.... , on

if 'title' in show , 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, have this

    if title not in shows:         show = shows[title] = {'episodes': []}  # new show dictionary     else:         show = shows[title]     if 'title' in show , title in show['title']:             ep = {'episode': episode, 'season': season}             ep['plays'] = played             show['episodes'].append(ep)     else: 

this give me output wanted wanted make sure looked correct

you need store matches in dictionary instead, keyed title. can find same show again if encounter in file more once:

shows = {}  # loop producing entries     if title not in shows:         show = shows[title] = {'episodes': []}  # new show dictionary     else:         show = shows[title]      # have `show` dictionary work     # add episodes directly `show['episodes']` 

after collecting shows, use shows.values() extract show dictionaries list.


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -