2

我想获得像这样的输出

{'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'}

但我被困在附加行上,因为我需要附加到字典中的一个值。如果标题不在字典中,它会为该标题创建第一个条目

{'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:

这给了我想要的输出,但只是想确保它看起来正确

4

1 回答 1

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()将所有节目词典提取为列表。

于 2013-08-10T11:01:12.380 回答