访问字典中列表的元素

0 投票
3 回答
516 浏览
提问于 2025-04-17 17:22

我正在尝试创建一个数据结构,用来记录每个月的发生次数,时间跨度是好几年。我觉得用一个字典里面放列表是最合适的选择。我想要的结构大概是这样的(年份: 一个包含十二个整数的列表,代表每个月的发生次数):

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.
}

我的代码会遍历第二个字典,首先关注键的前四个字符(也就是年份),如果这个年份不在字典里,我就会初始化这个键,并把它的值设为一个包含十二个月份的空列表:[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' is not callable(字典不可调用) 2. KeyError: 2009(键错误:2009)

如果需要我进一步解释,请告诉我。谢谢你的关注。

3 个回答

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 并没有什么帮助。我重新写了答案,只是用默认获取的方法,并且复制了那个列表。

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]}
>>> 
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]

注意,我假设你日期格式中的一月份是 01 而不是 00,如果不是这样的话,只需在最后一行用 dmonth 替换 dmonth-1 就可以了。

撰写回答