Question

I am working with a large dictionary (500+ keys) that has as its values 2 dictionaries (that have as their values numerics) and two lists (one of numerics with length=~10, one of bools with length=~50). I would like to get some sort of representation, be it a list or tuple, that sorts the original dictionary by one of the numeric values inside of one of the inner dictionaries. Is there a way to do this?

For reference, here is a single entry for key 'WHR' from the (large) dictionary I am working with:

dd_rf['WHR'] = {'counts': {'num': 81.0,
  'numClassCorrect': 64,
  'numClassDown': 20,
  'numClassDownCorrect': 20,
  'numClassIncorrect': 17.0,
  'numClassUp': 61,
  'numClassUpCorrect': 44,
  'numDown': 37,
  'numUp': 44},
 'imp': array([ 0.50924113,  0.06348138,  0.07851569,  0.03005051,  0.04103215,
        0.05646218,  0.03682958,  0.03642228,  0.04282599,  0.01439416,
        0.03090185,  0.0598431 ]),
 'rates': {'correctDownRate': 1.0,
  'correctRate': 0.7901234567901234,
  'correctUpRate': 0.7213114754098361,
  'downRate': 0.4567901234567901,
  'upRate': 0.5432098765432098},
 'results': array([False, False,  True,  True,  True,  True, False, False,  True,
       False,  True,  True, False, False,  True, False,  True,  True,
        True,  True,  True,  True,  True,  True,  True, False, False,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True, False,  True, False, False,  True,  True,  True,  True,
        True,  True,  True,  True, False,  True, False,  True,  True,
        True,  True,  True, False, False, False,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True, False,  True,
        True,  True, False,  True,  True,  True,  True,  True,  True], dtype=bool)}

So, in the context of my work, I would like to sort the entire dictionary 'dd_rf' by the values of 'dd_rf[key]['rates']['correctRate'] in descending order. The value corresponding to the given sort criteria in the above example is 'correctRate': 0.7901234567901234.

Thanks! Please let me know if I can provide any more background information.

Was it helpful?

Solution

I'm not sure what the final form you're looking for is, since stuffing the result back into a dictionary will lose the ordering. Perhaps look into collections.OrderedDict. However, the basic idea is to just turn your dictionary into a list and then sort that list with your custom function. e.g.

answer = sorted(dd_rf.items(), key=lambda (k,v): v['rates']['correctRate'])

That's the general idea. You may want to start by seeing how something like

sorted(range(10), key=lambda x: (x-5)**2)

works to build up your understanding.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top