Python sorted()

Sort by data value in the list of dict

data = [
        {
            'id': 999,
            'author': '@gmail',
            'title': 'First',
            'content': '1 content goes here'
        },
        {
            'id': 555,
            'author': '@hotmail',
            'title': 'Second',
            'content': '2 content goes here'
        },
        {
            'id': 111,
            'author': '@outlook.com',
            'title': 'Third',
            'content': '3 content goes here'
        },
    ]
sortedData = sorted(data , key=lambda d: d['id'])
sortedDataR = sorted(data , key=lambda d: d['id'], reverse=True)

Sort by using itemgetter

from operator import itemgetter

sortedData = sorted(data, key=itemgetter('id'))
sortedData = sorted(data, key=itemgetter('author'))
sortedData = sorted(data, key=itemgetter('title'))

Sort by attribute value in class

class Employee():

    def __init__(self, name, age, salary):
        self.name = name
        self.age = age
        self.salary = salary

    def __repr__(self):
        return '{} {} {} '.format(self.name, self.age, self.salary)


e1 = Employee('Kim', '99', 1)
e2 = Employee('John', '98', 2)
e3 = Employee('Sarah', '97', 3)

employees = {e1, e2, e3}

print("Sorted employees: ", sorted(employees, key=lambda e: e.name))

Sort by using attrgetter

from operator import attrgetter

print("Sorted employees with attrgetter: ", sorted(employees, key=attrgetter('age')))
print("Sorted employees with attrgetter: ", sorted(employees, key=attrgetter('name')))
print("Sorted employees with attrgetter: ", sorted(employees, key=attrgetter('salary')))

list

li = [6, 4, 9, 1, 2, 5, 7, 8, 3]

s_li = sorted(li, reverse=True)

print("Sorted variable: ", sorted(li))
print("Sorted variable in reverse: ", sorted(li, reverse=True))

tuple

tup = [6, 4, 9, 1, 2, 5, 7, 8, 3]
print("Sorted tuple: ", sorted(tup))
print("Sorted tuple in reverse: ", sorted(tup, reverse=True))

sort dict by key

dict = {
    'name':'Kim',
    'job':'Technical',
    'age':'99',
    'os':'Win10'
}
print("Sorted dict: ", sorted(dict))

sort by absolute value

li = [6, -4, 9, -1, 2, -5, 7, 8, 3]
print("Sort by absolute value: ", sorted(li, key=abs))

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top