appel
appel

Reputation: 537

Sort a nested dict into an ordered list in Python 2.7

I have the following dict:

d = {'d_1': {'score': 5.2, 'concept': 'a'}, 
     'd_2': {'score': 10.1, 'concept': 'e'}, 
     'd_3': {'score': 1.5, 'concept': 'c'}, 
     'd_4': {'score': 20.2, 'concept': 'd'}, 
     'd_5': {'score': 0.9, 'concept': 'b'}}

I want to get a sorted list, by score, like so:

d_sorted = [{'d_4': {'score': 20.2, 'concept': 'd'}},
            {'d_2': {'score': 10.1, 'concept': 'e'}},
            {'d_1': {'score': 5.2, 'concept': 'a'}},
            {'d_3': {'score': 1.5, 'concept': 'c'}},
            {'d_5': {'score': 0.9, 'concept': 'b'}}]

I tried the following, but that will sort by concept, not score:

d_sorted = sorted(d.items(), key=operator.itemgetter(1), reverse=True)

How would I sort this nested dict by the score key (descending) into an ordered list in Python 2.7?

EDIT: This is not a duplicate of Sort a nested dict into an ordered list in Python 2.7 because it concerns nested dicts.

Upvotes: 2

Views: 265

Answers (1)

eumiro
eumiro

Reputation: 212835

Extract the value first:

[{k: v} for k, v in sorted(d.items(), key=(lambda x: x[1]['score']), reverse=True)]

Upvotes: 5

Related Questions