附加到字典中的列表 [英] Append to a list within a dictionary
问题描述
我想获得输出像
{'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)
感谢Martijn Pieters,I现在有这个
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
推荐答案
你需要存储您的匹配在字典中,而是按标题键入。如果您多次在文件中遇到相同的节目,您可以再次找到相同的节目:
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']`
收集所有节目后,请使用 shows.values()
提取所有显示词典作为列表。
After collecting all your shows, use shows.values()
to extract all show dictionaries as a list.
这篇关于附加到字典中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!