How to delete keys from dictionary by their values

Question:

students = {'palii':('male','170'),
            'Minckach':('male','176'),
            'ddl':('male','180'),
            'Red1ska':('male','188'),
            'Sargeras':('male','185'),
            'Gerus':('female','160'),
            'Liah':('male','183'),
            'Chhekan':('female','182'),
            'Leshega':('male','186'),
            'yurii':('male','187')}

I have this dictionary. How can i delete all the females from it and calculate males average height? Maybe there is a function or something that idk?

I tried using filter() like

newDict = dict(filter(lambda elem: elem[1] == 'male',students.items()))

But this is not working.

def halfmale(stats): 
    sum = 0
    for key in stats.values():
        sum += float(key)
    half = sum / len(stats)
    print(half)
    for value, key in stats.items():
        if (key+5>half and key-5<half):
            print(value)

Python says that promlem is division by zero in this part

Asked By: B3SUS

||

Answers:

Are you wanting this?

  1. Iterate over dict.
  2. Keep height if gender =='male'.
  3. Compute the average.
height_lst = [int(height) for name, (gender, height) in students.items() if gender == 'male']
print(f'Average: {sum(height_lst)/len(height_lst)}') 

Output:Average: 181.875

You can correct newDict like the below:

>>> dict(filter(lambda elem: elem[1][0] == 'male',students.items()))

{'palii': ('male', '170'),
 'Minckach': ('male', '176'),
 'ddl': ('male', '180'),
 'Red1ska': ('male', '188'),
 'Sargeras': ('male', '185'),
 'Liah': ('male', '183'),
 'Leshega': ('male', '186'),
 'yurii': ('male', '187')}
Answered By: I'mahdi

Use dict comprehension to make a new dict including only males.

newDict = {k:v for k,v in students.items() if v[0] == 'male'}
Answered By: John Gordon
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.