I have the the following list:
list = [{'nr' : 2, 'name': 'streamname'}, {'nr' : 3,'name': 'streamname'}, {'nr' : 1, 'name': 'streamname'}]
So how would I reorder it to become like this in an efficient way in python?
list = [{'nr' : 1, 'name': 'streamname'}, {'nr' : 2,'name': 'streamname'}, {'nr' : 3, 'name': 'streamname'}]
I came up with using sort and creating a lambda function to sort it. Is this a good way? And is it efficient?
list.sort(cmp=lambda x,y: cmp(x['nr'], y['nr']))
No, using
cmp=is not efficient. Usekey=instead. Like so:The reason is simple:
cmpcompares two objects. If your list is long, there are many combinations of two objects you can have to compare, so a list that is twice as long takes much more than twice as long to sort.But with
keythis is not the case and sorting long lists are hence much faster.But the main reason to use
keyinstead ofcmpis that it’s much easier to use.Also,
sorted() has a benefit over.sort(), it can take any iterable, while.sort()inly works on lists.