Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fix 'int object is not iterable' from a function

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’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading