Sort list by list attribute

I know there are several posts about sorting python lists, but I tried a bunch of things and couldn't achieve what I want.

My code is:

list = [] things = re.findall('<a class="th tooltip" data-rel=.*? href="(.*?)".*?> <img src="(.*?)" alt="(.*?)" .*?', content, re.DOTALL) for url, image, name in things: list.append({'url': url, 'image': image, 'name': name}) 

Now I want to sort this list by name. I found several posts that claimed to use list.sort(key=) , but I don't know what I should use for the key. All I tried led to a KeyError .

I apologize if I duplicate an already authorized post, but I cannot find a suitable solution.

Thanks in advance.

+5
source share
1 answer

Use the lambda expression, the lambda expression will get the dictionary as a parameter, and then you can return the name element from the dictionary -

 lst.sort(key=lambda x: x['name']) 

Also, do not use list as a variable name, it will overwrite the built-in list function, which can cause problems when trying to use the list(..) function.

+2
source

All Articles