What is the pythonic way to reorder a list consisting of dicts?

I have the following list:

list = [{'nr' : 2, 'name': 'streamname'}, {'nr' : 3,'name': 'streamname'}, {'nr' : 1, 'name': 'streamname'}] 

So, how would I change its order to make it efficient in python?

 list = [{'nr' : 1, 'name': 'streamname'}, {'nr' : 2,'name': 'streamname'}, {'nr' : 3, 'name': 'streamname'}] 

I came up with sorting and creating a lambda function to sort it. Is this a good way? And is it effective?

 list.sort(cmp=lambda x,y: cmp(x['nr'], y['nr'])) 
+4
source share
2 answers

No, using cmp= inefficient. Use key= instead. For instance:

 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 that you can compare, so a list that is twice as long takes much more than twice as much to sort.

But this is not the case with key , and sorting long lists is much faster.

But the main reason for using key instead of cmp is that it is much easier to use.

In addition, sorted () takes precedence over .sort() , it can take any iteration, and .sort() only works on lists.

+12
source
 mylist.sort(key=operator.itemgetter('nr')) 
+3
source

Source: https://habr.com/ru/post/1334929/


All Articles