0

Really struggling on how to sort a nested dictionary alphabetically only using its sub-keys. I cannot find an analogous question on here.

For instance I have:

people = {5: {'first': 'John', 'age': '27', 'last': 'Doe'},
          2: {'first': 'Marie', 'age': '22', 'gender': 'Female'}}

But want:

people = {5: {'age': '27','first': 'John', 'last': 'Doe'},
          2: {'age': '22','first': 'Marie', 'gender': 'Female'}}

Attempt:

import OrderedDict from collections
for d in people:
   people[d] = OrderedDict(sorted(d.items()))
AttributeError: 'int' object has no attribute 'items'
Andrea
  • 607
  • 8
  • 21
  • Please mention the stuff you've tried, your progress and the errors you encountered. See https://stackoverflow.com/help/how-to-ask – Aditya Agrawal Sep 21 '19 at 16:48
  • Possible duplicate of [How can I sort a dictionary by key?](https://stackoverflow.com/questions/9001509/how-can-i-sort-a-dictionary-by-key) – Aditya Agrawal Sep 21 '19 at 16:52

1 Answers1

1

I figured it out:

import OrderedDict from collections

for data_center in dc_error_modes:
    d = dc_error_modes[data_center]
    dc_error_modes[data_center] = OrderedDict(sorted(d.items()))
Andrea
  • 607
  • 8
  • 21