我想获得像
这样的输出{'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'}
但我被困在追加线上,因为我需要附加到字典中的值。 如果title不在字典中,则会为该标题创建第一个条目
{'episodes': [{'season': 1, 'plays': 0, 'episode': 12}], 'title': 'Third Reich: The Rise & Fall', 'imdb_id': 'tt1855924'}
然后如果再次出现相同的标题,我想要将季节,剧集和戏剧插入到现有的行中。然后该脚本将执行下一个节目并创建一个新条目,或者如果已经有该标题的条目,则再次附加....等等
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)
感谢Martijn Pieters,我现在有了这个
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:
这给了我想要的输出,但只是想确保它看起来正确
答案 0 :(得分:1)
您需要将匹配项存储在词典中,并按标题键入。如果您在文件中多次遇到该节目,则可以再次找到相同的节目:
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']`
收集完所有节目后,使用shows.values()
将所有节目词典提取为列表。