+ 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
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')])
+ 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.
+ 2
oh many thanks. that have i tried at first and not noticed my mistake in the dict.