How to make and average of all ages in dictionary?

Question:

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

Asked By: Robert

||

Answers:

you can try something like:

ages = [user['age'] for user in user_list if user['gender'] == 'f']
avg = sum(ages) / len(ages)
Answered By: Nowtilous overflow

not entirely sure if this is what you are looking for, but maybe try with two dicts:

cont = {'m': 0, 'f': 0}
avgs = {'m': 0, 'f': 0}

for u in user_list:
    gdr = u['gender']
    if not gdr:
        continue
    cont[gdr] += 1
    avgs[gdr] += u['age']

for g in avgs:
    avgs[g] /= cont[g]

print(avgs)  # {'m': 24.0, 'f': 34.0}
Answered By: rv.kvetch
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()
Answered By: Valerii

you can try something like this. As you can also have None for the age. Try using .get method for a dict.

total_age = 0
for user in user_list:
    if user.get('age'):
       total_age = total+user['age']
avg_age = total_age/len(user_list)

Hope it helps!!

Answered By: Priyanka Jain

If you have trouble understanding lambda, this can be another option.

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},
] 

ages = []

def user_stat():
    for age in user_list:
        if isinstance(age["age"], int):
            ages.append(age["age"]) # If the age is an integer, add it to a list.
    
    average = sum(ages) / len(ages) # Creates average by dividing the sum with the length of the list

    print(f"The age average is {average}") 
    
user_stat()
Answered By: Bacon_Wizard
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.