Sort dicts (contained in lists) alphabetically in Python

I am having trouble sorting a list containing a dict. I am currently sorting it using a key called "title" with the following line:

list.sort(key=operator.itemgetter('title'))

The problem is that some of my data is sorted as follows:

title_text #49
title_text #5
title_text #50

How can I sort it in a way that is friendlier for human consumption, while preserving the sorting of the headers?

+3
source share
3 answers

You are looking for sorting people .

import re
# Source: http://nedbatchelder.com/blog/200712/human_sorting.html
# Author: Ned Batchelder
def tryint(s):
    try:
        return int(s)
    except:
        return s

def alphanum_key(s):
    """ Turn a string into a list of string and number chunks.
        "z23a" -> ["z", 23, "a"]
    """
    return [ tryint(c) for c in re.split('([0-9]+)', s) ]

def sort_nicely(l):
    """ Sort the given list in the way that humans expect.
    """
    l.sort(key=alphanum_key)

data=[
    'title_text #49',
    'title_text #5',
    'title_text #50']
sort_nicely(data)
print(data)
# ['title_text #5', 'title_text #49', 'title_text #50']

Edit: If yours datais a list of dicts, then:

data=[{'title': 'title_text #49', 'x':0},
      {'title':'title_text #5', 'x':10},
      {'title': 'title_text #50','x':20}]

data.sort(key=lambda x: alphanum_key(x['title']))
# [{'x': 10, 'title': 'title_text #5'}, {'x': 0, 'title': 'title_text #49'}, {'x': 20, 'title': 'title_text #50'}]
+4
source

You will have to parse this integer from the header manually. This function will do it.

def parse_title_num(title):
   val = 0
   try:
      val = int(title.rsplit('#')[-1])
   except ValueError:
      pass
   return val


 list.sort(key=lambda x: parse_title_num(x['title'])
0
source

Source: https://habr.com/ru/post/1754284/


All Articles