我想获得类似的输出

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


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

最佳答案

您需要将匹配项存储在字典中,并按标题键。如果您在文件中多次遇到相同的节目,则可以再次找到该节目:

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

关于python - 附加到词典中的列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18160906/

10-09 20:21