Working Ninja
2019-01-26T09:36:57
Sort Dictionary by Nested Dictionary Value

Objective: Sort dictionary by nested dictionary value

Let's say we want to sort the following JSON by the nested dictionary value of count.

{
  "Mail": {
    "count": 20,
    "users": ["lukeskywalker", "darthvader"]
  },
  "Droid Sync": {
    "count": 5,
    "users": ["lukeskywalker"]
  }
}

Method 1: lambda

apps_sorted = sorted(apps.items(), key=lambda x: (x[1]['count']))

Method 2: key function

def sort_by_count(x):
    # key=lambda x: (x[1]['count'])
    key, data = x
    return data['count']

apps_sorted = sorted(apps.items(), key=sort_by_count)

Source: https://stackoverflow.com/questions/4110665/sort-nested-dictionary-by-value-and-remainder-by-another-value-in-python