5

I have a dictionary something looks like this

{
'Host-A': {'requests': 
    {'GET /index.php/dashboard HTTP/1.0': {'code': '200', 'hit_count': 3},
     'GET /index.php/cronjob HTTP/1.0': {'code': '200', 'hit_count': 4},
     'GET /index.php/setup HTTP/1.0': {'code': '200', 'hit_count': 2}},
'total_hit_count': 9},
}

as you can see for 'Host-A' the value is a dict contains requests received and hits count on each page.. the question is how to sort the 'requests' in descending order. so then I can get the top requests .

example of correct solution output would be like:

{
'Host-A': {'requests':
    {'GET /index.php/cronjob HTTP/1.0': {'code': '200', 'hit_count': 4},
     'GET /index.php/dashboard HTTP/1.0': {'code': '200', 'hit_count': 3},
     'GET /index.php/setup HTTP/1.0': {'code': '200', 'hit_count': 2}},
'total_hit_count': 9},
}

I appreciate your help

Prune
  • 76,765
  • 14
  • 60
  • 81
Manix
  • 93
  • 7
  • python dictionaries are key-value pairs and are not sorted in any way. You can use `OrderedDict` if you want though: https://docs.python.org/3/library/collections.html#ordereddict-objects – aikikode Apr 19 '19 at 16:33
  • @Gassa I have modified the questions. – Manix Apr 19 '19 at 16:39

1 Answers1

4

Assuming you're using Python 3.7+, where the order of dict keys are preserved, and given your dict stored in variable d, you can sort the items of the d['Host-A']['requests'] sub-dict with a key function that returns the hit_count value of the sub-dict in the second item of the given tuple, and then pass the resulting sorted sequence of items to the dict constructor to build a new sorted dict:

d['Host-A']['requests'] = dict(sorted(d['Host-A']['requests'].items(), key=lambda t: t[1]['hit_count'], reverse=True))
blhsing
  • 91,368
  • 6
  • 71
  • 106