我正在尝试打开这本词典:
dic = {'2007-10-21': '53', '2007-10-28': '50', '2007-11-05': '100','2007-11-06': '99'}
变成这样的东西:
dic = {'2007-10': '103', '2007-11': '199'}
因为我需要按比例执行此操作,所以从Python的角度来说,我需要将其键以相同的7个字符开头的所有值相加。
尝试这个,
__author__ = 'Fawzan'
dic = {'2007-10-21': '53', '2007-10-28': '50', '2007-11-05': '100', '2007-11-06': '99'}
# create a new dictionary
newDic = {}
# iterate the old dictionary
for key in dic:
# get the desiresd string for comparision
k = key[0:7]
# for debug
print(k)
# if the key is already in the new dictionary, then add the value to existing key
if (k in newDic):
newDic[k] += float(dic[key])
# else append the key, value
else:
newDic[k] = float(dic[key])
# print and check the answer :)
print(newDic)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句