Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Pythonic way of reordering a list consisting of dicts?

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']))
like image 879
Sam Stoelinga Avatar asked Dec 07 '22 00:12

Sam Stoelinga


2 Answers

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.

like image 92
Lennart Regebro Avatar answered Feb 23 '23 00:02

Lennart Regebro


mylist.sort(key=operator.itemgetter('nr'))
like image 21
nosklo Avatar answered Feb 23 '23 00:02

nosklo