Friday, December 27, 2013

Python - Sorting a list of objects

Assuming I have a list of JSON objects:

obj1 = {'title': 'Super genius', 'modifiedDate': 1334014208.0, 'user_id': 123}

obj2 = {'title': 'Awesome', 'modifiedDate': 1333962645.0, 'user_id': 345}

obj3 = {'title': 'Gorgeous', 'modifiedDate': 1333894106.0, 'user_id': 531}

obj4 = {'title': 'Cool', 'modifiedDate': 1333968061.0, 'user_id': 214}

obj5 = {'title': 'Badass', 'modifiedDate': 1334016506.0, 'user_id': 678}


unorder_list = [obj4, obj5, obj1, obj2, obj3]


And I want to create a list contains those objects in ascending order of modifiedDate.


1. Solution #1: using lambda to sort by 'modifiedDate'

def order_list():
    order_list = unorder_list
    order_list.sort(key = lambda x: x['modifiedDate'])
    return order_list


2. Solution #2: do not use lambda

def order_list():
    order_list = []
    tmp = {}
    for i in unorder_list:
        tmp[i['modifiedDate']] = i
    tmp2 = tmp.keys()
    tmp2.sort()
    for k in tmp2:
        order_list.append(tmp[k])

    return order_list