访问列表字典中的列表项

Mil*_*oln 0 python dictionary

我正在尝试创建一个数据结构,用于跟踪多年来每月发生的事件.我已经确定列表是最好的选择.我想创建类似这种结构的东西(年份:代表每月出现次数的十二个整数的列表):

yeardict = {
'2007':[0,1,2,0,3,4,1,3,4,0,6,3]
'2008':[0,1,2,0,3,4,1,3,5,0,6,3]
'2010':[7,1,3,0,2,6,0,6,1,8,1,4]
}
Run Code Online (Sandbox Code Playgroud)

我作为输入,一个看起来像这样的字典:

monthdict = {
'2007-03':4,
'2007-05':2,
'2008-02':8
etc.
}
Run Code Online (Sandbox Code Playgroud)

我的代码循环通过第二个字典,首先注意键中的前4个字符(年份),如果不在字典中,那么我将该键与列表中的12个空白月份的值初始化form:[0,0,0,0,0,0,0,0,0,0,0,0],然后将该月份位置列表中的项目值更改为该值.如果年份在字典中,那么我只想将列表中的项目设置为等于该月份的值.我的问题是如何在字典中的列表中访问和设置特定项目.我遇到了一些对谷歌没有特别帮助的错误.

这是我的代码:

    yeardict = {}
    for key in sorted(monthdict):
        dyear = str(key)[0:4]
        dmonth = str(key)[5:]
        output += "year: "+dyear+" month: "+dmonth
        if dyear in yeardict:
            pass
#            yeardict[str(key)[0:4]][str(key)[5:]]=monthdict(key)                
        else:
            yeardict[str(key)[0:4]]=[0,0,0,0,0,0,0,0,0,0,0,0]
#            yeardict[int(dyear)][int(dmonth)]=monthdict(key)
Run Code Online (Sandbox Code Playgroud)

注释掉的两行是我想要实际设置值的地方,当我将它们添加到我的代码时,它们会引入两个错误之一:1.'dict'不可调用2. KeyError:2009

如果我能澄清任何事情,请告诉我.谢谢你的期待.

And*_*ark 5

我是这样写的:

yeardict = {}
for key in monthdict:
    try:
        dyear, dmonth = map(int, key.split('-'))
    except Exception:
        continue  # you may want to log something about the format not matching
    if dyear not in yeardict:
        yeardict[dyear] = [0]*12
    yeardict[dyear][dmonth-1] = monthdict[key]
Run Code Online (Sandbox Code Playgroud)

请注意,我假设您的日期格式的1月01不是00,如果不是这种情况,则只使用dmonth而不是dmonth-1在最后一行.