将数据添加到Dict

时间:2017-05-25 07:31:38

标签: python python-3.x dictionary

所以,我正在尝试构建一个Flask应用程序来跟踪我的电视节目(只是为了好玩)...但是现在我正在尝试处理API本身(TVmaze),我是以“箭头”为例。我想要做的是创建dict这样all_seasons = {season_number:{'ep_number':{'ep_name':'Exemple...', ep_num: ep_number}}},所以例如,如果我想获得第4季第22集的名字,我会这样做all_seasons[4][22]['ep_name'] 不知怎的,我设法做到了(有点),但这就是我得到的:

{1: {23: {'ep_name': 'Sacrifice', 'ep_num': 23}},
2: {23: {'ep_name': 'Unthinkable', 'ep_num': 23}},
3: {23: {'ep_name': 'My Name is Oliver Queen', 'ep_num': 23}},
4: {23: {'ep_name': 'Schism', 'ep_num': 23}},
5: {23: {'ep_name': 'Lian Yu', 'ep_num': 23}}}

我只收到了每个季节的第23集。我正在使用的代码:

for i in range(len(seasonNum) +1):
    while e <= total2:
        if e_data[e]['season'] == i+1:
            temp = i + 1
            ep_num = e_data[e]['number']
            ep_title = e_data[e]['name']
            all_seasons[temp] = {ep_num:{'ep_name':ep_title, 'ep_num':ep_num}}
            print("Season %d Episode %d - %s"%(temp, ep_num, ep_title))
        else:
            i+=1
        e+=1

我将打印声明仅用于调试,并且打印工作正常。显示每季的所有剧集

Season 1 Episode 1 - Pilot
Season 1 Episode 2 - Honor Thy Father
Season 1 Episode 3 - Lone Gunmen
Season 1 Episode 4 - An Innocent Man
Season 1 Episode 5 - Damaged
Season 1 Episode 6 - Legacies
Season 1 Episode 7 - Muse of Fire
Season 1 Episode 8 - Vendetta
Season 1 Episode 9 - Year's End
Season 1 Episode 10 - Burned
Season 1 Episode 11 - Trust But Verify
Season 1 Episode 12 - Vertigo
Season 1 Episode 13 - Betrayal
Season 1 Episode 14 - The Odyssey
...

它继续。

1 个答案:

答案 0 :(得分:0)

您正在替换每次迭代的字典,而不是添加新数据。尝试这样的事情:

i = 0
e = 0
while e <= total2:
    if e_data[e]['season'] == i+1:
        temp = i + 1
        ep_num = e_data[e]['number']
        ep_title = e_data[e]['name']
        all_seasons.setdefault(temp, {})[ep_num] = {'ep_name':ep_title, 'ep_num':ep_num}}
        print("Season %d Episode %d - %s"%(temp, ep_num, ep_title))
        e += 1
    else:
        i +=1

all_seasons.setdefault(temp, {})只会在all_seasons中添加一个新条目,其中包含密钥temp和值{},只有它已经不存在,然后返回all_seasons[temp] (已存在的值或新设置的值)(参见dict.setdefault)。