1
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

wjandrea
  • 28,235
  • 9
  • 60
  • 81
B3SUS
  • 13
  • 3
  • 2
    your filter idea would work if it was `elem[1][0]` instead of just `elem[1]` in the lambda or you could do `'male' in elem[1]` – Alexander Nov 04 '22 at 19:07
  • Beside the point, but [I recommend avoiding `filter(lambda)`](/a/61945553/4518341); use a comprehension instead, i.e. `dict(elem for elem in students.items() if elem[1][0] == 'male')` or `{k:v for k,v in students.items() if v[0] == 'male'}`. – wjandrea Nov 04 '22 at 19:18

2 Answers2

1

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')}
I'mahdi
  • 23,382
  • 5
  • 22
  • 30
0

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

newDict = {k:v for k,v in students.items() if v[0] == 'male'}
John Gordon
  • 29,573
  • 7
  • 33
  • 58