I am trying to sort a recursively sort a 2 level nested default dict. I have not been able to figure out how to do this properly. My problem statement is given below:
- First level key must be a natural sort.
-
Second level key must be sorted in a specific order. I have tried to create a list whose indices represent the order of the elements. My code snippet is given below:
import operator import collections trade_group_totals = collections.defaultdict(lambda:collections.defaultdict(float)) trade_group_totals['foo']['ABC'] = 100 trade_group_totals['foo']['XYZ'] = 50 trade_group_totals['bar']['ABC'] = 150 trade_group_totals['bar']['XYZ'] = 250
My sorting index comparison:
trade_groups = ['XYZ', 'ABC']
def TradeGroupSort(trade_group):
return trade_groups.index(trade_group)
def SortTotals(totals, sort_function_one, sort_function_two):
return [
(k1, v1) for k1, v1 in [(k, sorted(v.iteritems(), key=sort_function_two))
for k, v in sorted(totals.iteritems(), key=sort_function_one)]]
I am invoking the function as follows:
SortTotals(
trade_group_totals, operator.itemgetter(0),
sort_function_two=lambda x: operator.methodcaller('TradeGroupSort', x))
My expected output should be:
[('bar', [('XYZ', 50), ('ABC', 100)]), ('foo', [('XYZ', 250), ('ABC', 150)])]
But the generated output is
[('bar', [('XYZ', 50), ('ABC', 150)]), ('foo', [('ABC', 150), ('XYZ', 250)])]
Unfortunately, none of the solutions worked for me. This is the UGLY sorting that I came up with.
I could not think of a better solution than that. I invoked this function as follows:
This returns the expected result.