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 make and average of all ages in dictionary?

I am new to python and I am trying to count the number of males and females in a list and that worked but I do not know how to make the average of all the ages in the list.

user_list = [
    {'name': 'Alizom_12',
     'gender': 'f',
     'age': 34,
     'active_day': 170},
    {'name': 'Xzt4f',
     'gender': None,
     'age': None,
     'active_day': 1152},
    {'name': 'TomZ',
     'gender': 'm',
     'age': 24,
     'active_day': 15},
    {'name': 'Zxd975',
     'gender': None,
     'age': 44,
     'active_day': 752},
] 

def user_stat():
    from collections import Counter
    counts = Counter((user['gender'] for user in user_list))
    print(counts) 

user_stat()

>Solution :

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

def user_stat():
    # Here we get rid of the None elements
    user_list_filtered = list(filter(lambda x: isinstance(x['age'], int), user_list))

    # Here we sum the ages and divide them by the amount of "not-None" elements
    print(sum(i.get('age', 0) for i in user_list_filtered) / len(user_list_filtered))

    # If you want to divide by None-elements included
    print(sum(i.get('age', 0) for i in user_list_filtered) / len(user_list))

user_stat()
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