1

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'
0

1 Answer 1

4

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})])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.