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 delete keys from dictionary by their values

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.

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

>Solution :

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