Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort list by attribute of list [duplicate]

I know that there are several posts regarding sorts of python lists, but I tried a large bunch of things and didn't accomplish to get what I want.

My code:

    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 which stated to use list.sort(key=) but I don't know what I should use for the key. Everything I tried resulted in a KeyError.

I'm sorry if I'm duplicating an already solved post, but I can't find the proper solution.

Thanks in advance.

like image 987
conFusl Avatar asked Jul 03 '15 09:07

conFusl


1 Answers

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

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

Also, please do not use the list as name of the variable, it will overwrite the built-in list function, which may cause issues when trying to use list(..) function.

like image 121
Anand S Kumar Avatar answered Sep 20 '22 11:09

Anand S Kumar