10

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.

5
  • 1
    Use a lambda function to map a list item i to i['name'], like so: key=lambda i: i['name'] Commented Jul 3, 2015 at 10:00
  • 3
    Preferrably, key=operator.itemgetter('name'). Commented Jul 3, 2015 at 10:01
  • @bereal: Even better :) Commented Jul 3, 2015 at 10:01
  • @bereal use operator.attrgetter('name') or it won't work on objects that aren't subscriptable Commented Nov 19, 2017 at 11:51
  • @Patrick attrgetter won't work on dicts, and that's what we're dealing with in this case. Commented Nov 19, 2017 at 11:53

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

wow, thx.. I figured out that I sorted on the wrong place, therefore I got two sublists sorted as output. THX
Use key=attrgetter('name') for better performance (import attrgetter from operator)
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.