9

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.

conFusl
  • 919
  • 6
  • 12

1 Answers1

3

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.

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
  • wow, thx.. I figured out that I sorted on the wrong place, therefore I got two sublists sorted as output. THX – conFusl Jul 03 '15 at 12:18
  • Use `key=attrgetter('name')` for better performance (import attrgetter from operator) – Patrick Nov 19 '17 at 11:51
  • `attrgetter` would not work in this , as we are working with dictionaries inside a list. But if you were going to do `getattr(x, 'name')` or `x.name` as key , then `attrgetter` would work . But don't really commend trying to optimize, unless you know this part is the bottleneck of the program. – Anand S Kumar Nov 20 '17 at 06:24