RKP
RKP

Reputation: 880

multi dimensional sorting in python

I am new to python, need an help to sort below multi-dimensional dictionary by field - "rank"

from operator import *
from collections import OrderedDict
print 'Dictionaries:'
l = {"test":{"rank":61,"test":2},"test1":{"rank":12,"test":2},"test2":{"rank":23,"test":2}}

I have tried with below approach,

d_sorted_by_value = OrderedDict(sorted(l.items(), key=attrgetter('rank')))

but getting error:

AttributeError: 'tuple' object has no attribute 'rank'

Upvotes: 1

Views: 180

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

You want to apply lambda to dict items, which is a tuple key/value. the value is the dict where you want to fetch "rank", so the sort key can be written as:

lambda d:d[1]["rank"]

(d[1] gives you the dict stored as then value and ['rank'] accesses the value-dict data). Confusion comes from the various degrees of dicts in the input data.

testing:

from collections import OrderedDict

l = {"test":{"rank":61,"test":2},"test1":{"rank":12,"test":2},"test2":{"rank":23,"test":2}}

d_sorted_by_value = OrderedDict(sorted(l.items(), key=lambda d:d[1]["rank"]))

print(d_sorted_by_value)

returns:

OrderedDict([('test1', {'rank': 12, 'test': 2}), ('test2', {'rank': 23, 'test':2}), ('test', {'rank': 61, 'test': 2})])

Upvotes: 4

Related Questions