Given a list of dictionaries like this:
x = [
{'name':'a', 'student': 1 , 'age':19},
{'name':'b', 'student': 0 , 'age':10}
]
I want to sort it by age only if student is equal to 1. Can I somehow put that if in the following statement?
sortedlist = sorted(x, key=lambda k: k['age'])
Thanks,
If you use itemgetter + a generator, instead of a lambda + list comp, you get the best performance I have found so far. This was tested on a dicts list of 10k elements. Almost a 30% speed increase over list comp + lambda. Also, if you can safely assume ‘student’ is always a valid key and access it directly, you again gain more speed over having to use
d.get('student', 0) == 1