I want to sort a list of dictionaries using the inbuilt sort() function for lists. The problem is I am not able to understand, how to give the function a key..

Example:

``````a={'name':1,'data':200}
b={'name':2,'data':400}
c=[a,b]``````

Now, I want to sort the list c with the key being a. If i use c.sort(), it gives me an error as dictionaries can not be compared. Either I can use a sorting algorithm but that would make my program too complex.
So, can anyone suggest me a beeter approach.

For me they sorted normally:
[CODE]a={'name':1,'data':200}
b={'name':2,'data':400}
c=[a,b]
print sorted(c,key=lambda x: x['name'])
[/CODE]

## All 6 Replies

For me they sorted normally:

``````a={'name':1,'data':200}
b={'name':2,'data':400}
c=[a,b]
print sorted(c,key=lambda x: x['name'])``````

OK, thanks. now I understood. Actually I was trying to give it a key like:

``````c.sort(key=a['name'])
#OR
c.sort(key=['name'])``````

It actually didn't strike me that I should be using a lambda function.

Can someone tell me the algorithm used by the functions sorted() and

• .sort()?

Can someone tell me the algorithm used by the functions sorted() and

• .sort()?

An adaptive merge sort is built into Python since version 2.3
It offers a good combination of high speed and stability.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.18 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.