from datetime import date

score_list = [
{ 2:date(2018,10,20), 5:date(2018,11,8), 0:date(2018,12,25),},
{ 3:date(2018,10,20), 1:date(2018,11,8), 4:date(2018,12,25),},
{ 0:date(2018,10,20), 1:date(2018,11,8), 0:date(2018,12,25),},
{ 2:date(2018,10,20), 7:date(2018,11,8), 3:date(2018,12,25),},
{ 0:date(2018,10,20), 0:date(2018,11,8), 6:date(2018,12,25),},
]

total = []
ave_total = []
ite=0

for i in score_list:
    sum = 0
    for key in i:
        sum+= key
    total.append(sum) 

print (total)

for j in total:
    **t = len(score_list[ite])
    ave = j/t
    print (t)**
    print (ite)
    ite += 1
    ave_total.append(ave) 
    print (ave)

print (ave_total)

while trying to use print to debug what went wrong i noticed that sometimes t returns as 2 while they are all the same length(3).

1 Answers

3
cdarke On

Keys in a dictionary are unique, you have no choice in that. So, for example:

{ 0:date(2018,10,20), 1:date(2018,11,8), 0:date(2018,12,25),},

only gives 2 keys because 0 is repeated.

EDIT: You need to restructure your data, since you will loose any duplicates in the way it is defined right now. There are several ways around this, here is one:

from datetime import date

score_list = [
{ 2:date(2018,10,20), 5:date(2018,11,8), 0:date(2018,12,25),},

{ 3:date(2018,10,20), 1:date(2018,11,8), 4:date(2018,12,25),},

#{ 0:date(2018,10,20), 1:date(2018,11,8), 0:date(2018,12,25),},
{ 0:[date(2018,10,20), date(2018,12,25)], 1:date(2018,11,8), },

{ 2:date(2018,10,20), 7:date(2018,11,8), 3:date(2018,12,25),},

#{ 0:date(2018,10,20), 0:date(2018,11,8), 6:date(2018,12,25),},
{ 0:[date(2018,10,20), date(2018,11,8)], 6:date(2018,12,25),},
]

This makes the keys with duplicate values use a list.

That means your simple len() is no longer adequate:

total = []
ave_total = []
ite = 0


for i in score_list:

    sum = 0

    for key in i:
        sum += key

    total.append(sum)

print(total)

for j in total:

    t = 0
    for val in score_list[ite].values():
        if isinstance(val, list):
            t += len(val)
        else:
            t += 1

    #t = len(score_list[ite])

    ave = j/t

    ite += 1

    ave_total.append(ave)

    print (ave)

print (ave_total)

You could simplify this if you created every value as a list.