Pavan Kumar T S
Pavan Kumar T S

Reputation: 1559

Sort data based on key of a list of multiple dictionaries

I have a list like this

li = [
    {1: {'amount': 255, 'date': '25-02-2017'}},
    {2: {'amount': 25, 'date': '2-02-2017'}},
    {3: {'amount': 38, 'date': '20-02-2017'}},
]

I am trying to sort the data in ascending and descending order based on 'amount'.

I tried the following but am unable to get the result I want:

import operator
li.sort(key=operator.itemgetter('amount'))

and

from operator import itemgetter
newlist = sorted(li, key=itemgetter('amount'))

Both raise an exception, KeyError: 'amount'.

Upvotes: 0

Views: 50

Answers (2)

Jayson Chacko
Jayson Chacko

Reputation: 2418

Try the following code which uses lambdas,

li=[{1:{'amount':255,'date':'25-02-2017'}},{2:{'amount':25,'date':'2-02-2017'}},{3:{'amount':38,'date':'20-02-2017'}}] 
print(li)

li.sort(key=lambda x:list(x.values())[0]['amount']) # ascending
print(li)

li.sort(key=lambda x:list(x.values())[0]['amount'],reverse=True) # descending
print(li)

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121386

You have a list of dictionaries with a single key, whose value is another dictionary. It is that nested dictionary that has the key 'amount'.

You'd have to reach in and get that single value:

newlist = sorted(li, key=lambda d: d.values()[0]['amount'])

This only works in Python 2, where d.values() is a list. In Python 3 you'd have to use next(iter(d.values())['amount'] instead.

You'd be much better of not producing the nested structure at all. Move those numbered keys into another key-value pair perhaps:

li = [
    {'id': 1', amount': 255, 'date': '25-02-2017'},
    {'id': 2, 'amount': 25, 'date': '2-02-2017'},
    {'id': 3, 'amount': 38, 'date': '20-02-2017'},
]

at which point your original attempt would work. You can transform your current data structure with [dict(id=d.keys()[0], **d.values()[0]) for d in li] but it'd be better to fix the code that produced the list.

Upvotes: 6

Related Questions