GrumpyCanuck
GrumpyCanuck

Reputation: 1438

Sorting a dict by values inside an inner dict in Python

My apologies if I am using the incorrect terminology, as I'm a bit of a Python n00b when it comes to the proper descriptions for data structures.

I have a data structure that looks like this:

{
    u'COU': {'hl': 39, 'hw': 42, 'winPct': Decimal('0.5471698113207547169811320755'), 'al': 36, 'l': 72, 'w': 87, 'aw': 45}, 
    u'MIN': {'hl': 42, 'hw': 39, 'winPct': Decimal('0.3559322033898305084745762712'), 'al': 57, 'l': 114, 'w': 63, 'aw': 24}, 
    u'BOW': {'hl': 36, 'hw': 44, 'winPct': Decimal('0.5432098765432098765432098765'), 'al': 37, 'l': 74, 'w': 88, 'aw': 44}
}

I want to sort this data structure by the value in winPct inside the inner dict and searching online has revealed a dazzling array of advice that makes no sense to this raised-on-PHP developer.

Thanks in advance for your help.

Upvotes: 0

Views: 265

Answers (2)

GWW
GWW

Reputation: 44103

You can't sort a dictionary, but you could convert the dictionary into a list of tuples with the form (key, value).

sorted_d = sorted(d.iteritems(), key=lambda v: v[1]['winPct'])

To Reverse the sorting as per your comment use:

sorted_d = sorted(d.iteritems(), key=lambda v: v[1]['winPct'], reverse=True)

Upvotes: 2

Gareth McCaughan
Gareth McCaughan

Reputation: 19981

Your data structure is a dictionary, and dictionaries don't have an ordering on the associations inside them, so I'm going to interpret "sort this data structure" to mean "make a list containing the (key,values) pairs from this data structure". This may or may not be what you want. So, first of all, get those pairs:

pairs = d.items()

(note: this returns a list in Python 2; I think it returns something else in Python 3, for which you'd need to call list() explicitly to make it into something you could sort, or call sorted instead of sort). Now sort according to your criterion:

pairs.sort(key = lambda (k,v): v['winPct'])

and now pairs contains what (perhaps) you want.

Upvotes: 0

Related Questions