+ 1

dict comprehension question

member = {'Mary': 42, 'John': 58, 'Max': 15, 'Sam': '4', 'Frank': 6, 'Lilli': 5} #***Question*** how can i get all names which starts with "M" , my attempt get not the right output print([name for (name,age) in member.items() if name >= "M"]) https://code.sololearn.com/cG07KBPt2Xga/?ref=app

5th Aug 2023, 1:25 PM
Angela
Angela - avatar
3 Answers
+ 5
Angela , you can try it like this: ... print([name for name in member.keys() if name[0] == 'M']) or we can use string method startswith(): print([name for name in member.keys() if name.startswith('M')])
5th Aug 2023, 7:47 PM
Lothar
Lothar - avatar
+ 2
I changed the last part of your print statement to: name >= "M" and name < "N"]) Also, I noticed that the age of Sam is not an integer. Not that it's related to your problem.
5th Aug 2023, 1:49 PM
Ausgrindtube
Ausgrindtube - avatar
+ 2
oh many thanks. that have i tried at first and not noticed my mistake in the dict.
5th Aug 2023, 2:14 PM
Angela
Angela - avatar