在有序字典中向键的值添加元素

2024-09-25 04:19:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本订好的字典:

{'20140106': '82.1000000',
 '20140217': '77.0300000',
 '20140224': '69.6200000',
 '20140310': '46.3300000',
 '20140414': '49.3800000',

键是日期:yyyy-mm-dd,我想在一个键中存储一个月的所有值:

^{pr2}$

我意识到这个不太好的解决方案:

val = []   #list, where i put all values for an exact month
previus_key = list(collection.keys())[0]
val.append(collection.get(previus_key))

for key in list(collection.keys())[1:]:
    if (key[4:6]==previus_key[4:6]):    #if it's the same month
        val.append(list(collection.pop(key)))             #remember the value and delete an item
    else:
        collection.update({previus_key:val})   #that means, we jumped to another month, so lets update the values for previus month 
        previus_key = key            #now, start the same algorihtm for a new month.
    val = collection.get(previus_key)

但是,我得到一个错误:'str' object has no attribute 'append'的行 val.append(list(collection.pop(key)))。我研究了一下,得出结论,它一定不在这里!因为,我把一个列表附加到一个列表中! 所以,请指出我的错误并给出建议,我怎样才能使代码更漂亮。谢谢!在


Tags: thekeyanforgetifvalkeys
3条回答

我不认为在这里使用字符串作为键来表示日期有任何好处。这是我的解决方案,但我希望它不会破坏您当前的代码。在

好吧,你的代码显示你在那里做了很多嵌套:

 val.append(list(collection.pop(key)))

以及:

Keys are dates: yyyy-mm-dd and i want to store all values of one month in one key:

以下是一种方法: 为此使用元组:

^{pr2}$

你不仅简化了代码,还简化了代码:

for date in mydict: 
    year  = date[0] 
    month = date[1] 
         ...
    ...process data...

虽然键只能是不可变的对象,但是元组是不可变的对象。在

为什么不使用reduce和{}函数。reduce将对迭代对象中的每个项应用一个函数,您还可以指定reduce的初始值

from collections import OrderedDict

a = {'20140106': '82.1000000', '20140217': '77.0300000', '20140224': '69.6200000', '20140310': '46.3300000', '20140414': '49.3800000'}


def aggr(result, item):
    key = filter(lambda x: x[:6] == item[0][:6], result.keys())
    if not key:
        result[item[0]] = [item[1]]
    else:
        result[key[0]].append(item[1])
    return result


r = OrderedDict()
print reduce(aggr, a.items(), r)

我认为问题出在你代码的最后一行。您确实在那里为变量var分配了一个字符串。在

编辑:这里有一个建议,它与您的原始代码很接近。

new_collection = {}
for key in collection:
    month = key[:6]
    if new_collection.get(month) != None:
        new_collection[month].append(collection[key])
    else:
        new_collection[month] = [collection[key]]

三件事: 1) 这里的结果是一个新的字典,而不是相同的实例,因为我发现它通常更可取。 2) 钥匙只有年份和月份,因为日期无关紧要。 3) 所有的值都是列表,而不是字符串和列表的混合。在

相关问题 更多 >