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. Use key=
instead. Like so:
sorted(list, key=lambda x: x['nr'])
The reason is simple: cmp
compares 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 key
this is not the case and sorting long lists are hence much faster.
But the main reason to use key
instead of cmp
is 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.
mylist.sort(key=operator.itemgetter('nr'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With