Here is how you could get the sorted list you are looking for:
items = ((k, k2, v) for k in d for k2, v in d[k].items())
ordered = sorted(items, key=lambda x: x[-1], reverse=True)
This first converts your dictionary into a generator that yields the tuples (key_1, key_2, value)
, and then sorts this based on the value. The reverse=True
makes it sort highest to lowest.
Here is the result:
>>> pprint.pprint(ordered)
[('library', 'lamp', 6),
('library', 'wall', 2),
('hain', 'facet', 1),
('hain', 'wrapp', 1),
('hain', 'chinoiserie', 1),
('library', 'sconc', 1),
('library', 'floor', 1),
('library', 'desk', 1),
('library', 'table', 1),
('library', 'maine', 1)]
Note that when the values match exactly, the order is arbitrary (except that items will always be grouped by key_1
), if you would like some other behavior just edit your question with what you expect in these scenarios.
After obtaining this list, you could print it out by iterating over it like this:
for key_1, key_2, value in ordered:
print key_1, key2, value # add whatever formatting you want to here