Home > Blockchain >  How to delete keys from dictionary by their values
How to delete keys from dictionary by their values

Time:11-05

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

CodePudding user response:

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')}

CodePudding user response:

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

newDict = {k:v for k,v in students.items() if v[0] == 'male'}
  • Related