I have a dict() like so
{'2020': [51000, 15000, 16000, 13000, 12000, 31000, 20000, 23000], '2021': [16000, 13000, 5000, 20000, 25000, 23000, 14000]}
and I want to run this function
def report(x,k):
for v in x.values():
the_sum = sum(v)
the_num = len(v)
for k,v in x.items():
if the_sum % the_num == 0:
x[k] = the_sum/the_num
else:
x[k] = the_sum//the_num
return x[k}
so that I can find the average of the value in the dict(), but I only got the average for ‘2020’
and I got this error for the ‘2021’
the_sum = sum(v)
TypeError: ‘int’ object is not iterable
>Solution :
I’m not sure why you’re iterating over all of the key-value pairs if you’re only trying to calculate the average for one key (as the function signature states).
If you want to compute the average value for a value, given a key and a dictionary, you can do the following:
data = {'2020': [51000, 15000, 16000, 13000, 12000, 31000, 20000, 23000], '2021': [16000, 13000, 5000, 20000, 25000, 23000, 14000]}
def report(x, k):
return sum(x[k]) // len(x[k])
print(report(data, '2020'))