访问列表字典中的列表项

时间:2013-02-27 21:43:03

标签: 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]
}

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

monthdict = {
'2007-03':4,
'2007-05':2,
'2008-02':8
etc.
}

我的代码循环通过第二个字典,首先注意键中的前4个字符(年份),如果不在字典中,那么我将该键和12个空白月的值初始化以列表形式:[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)

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

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

3 个答案:

答案 0 :(得分: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]

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

答案 1 :(得分:0)

defaultlist = 12*[0]
years = {}
monthdict = {
'2007-03':4,
'2007-05':2,
'2008-02':8
}

for date, val in monthdict.items():
    (year, month) = date.split("-")
    occurences = list(years.get(year, defaultlist))
    occurences[int(month)-1] = val
    years[year] = occurences

编辑实际上,defaultdict无济于事。重新写了答案,只做一个默认的获取并制作该列表的副本

答案 2 :(得分:0)

这是否有您想要的行为?

>>> yeardict = {}
>>> monthdict = {
... '2007-03':4,
... '2007-05':2,
... '2008-02':8 }
>>> for key in sorted(monthdict):
...     dyear = str(key)[0:4]
...     dmonth = str(key)[5:]
...     if dyear in yeardict:
...         yeardict[dyear][int(dmonth)-1]=monthdict[key]
...     else:
...         yeardict[dyear]=[0]*12
...         yeardict[dyear][int(dmonth)-1]=monthdict[key]
... 
>>> yeardict
{'2008': [0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], '2007': [0, 0, 4, 0, 2, 0, 0, 0, 0, 0, 0, 0]}
>>> 
相关问题