You cannot sort the dict because the dictionary does not order.
Use collections.OrderedDict instead:
>>> from collections import OrderedDict >>> d = {'Gears of war 3': 6, 'Batman': 5, 'gears of war 3': 4, 'Rocksmith': 5, 'Madden': 3} >>> od = OrderedDict(sorted(d.items(), key=lambda x:x[1], reverse=True)) >>> od OrderedDict([('Gears of war 3', 6), ('Batman', 5), ('gears of war 3', 4), ('Rocksmith', 5), ('Madden', 3)]) >>> od.keys() ['Gears of war 3', 'Batman', 'gears of war 3', 'Rocksmith', 'Madden'] >>> od.values() [6, 5, 4, 5, 3] >>> od['Batman'] 5
The "order" that you see in the JSON object does not make sense because the JSON object is unordered [ RFC4267 ].
If you need meaningful order in your JSON, you need to use a list (which is sorted as you wish). Something like this is what you want:
{ "count": 24, "top 5": [ {"Gears of war 3": 6}, {"Batman": 5}, {"Rocksmith": 5}, {"gears of war 3": 4}, {"Madden": 3} ] }
Given the same dict d , you can create a sorted list (which you want):
>>> l = sorted(d.items(), key=lambda x:x[1], reverse=True) >>> l [('Gears of war 3', 6), ('Batman', 5), ('Rocksmith', 5), ('gears of war 3', 4), ('Madden', 3)]
Now you just pass l to m['top5'] and unload it:
m["Top 5"]= l k = json.dumps(m)