Abid A Abid A - 3 months ago 19
Python Question

Sort nested dictionaries then sort outer dictionary

I have a dictionary of states and counties:

{
'WI': {'CountyZ': 0,
'CountyC': 0,
'CountyD': 0},
'IL': {'CountyM': 0,
'CountyW': 0,
'CountyA': 0}
}


I would like to sort the inner dictionaries of counties based on keys and then sort the outer dictionary of states based on the keys as well.

I've tried the following but I'm unable to get the desired result:

sorted(sorted(states.items(), key=lambda x: x[0]), key=lambda y: y[1].items())


I would like to get something like this:

[('IL', [('CountyA', 0), ('CountyM', 0), ('CountyW', 0)]),
('WI', [('CountyC', 0), ('CountyD', 0), ('CountyZ', 0)])]

Answer

You can get the sorted list of tuples like so:

d = {
  'WI': {'CountyZ': 0,
         'CountyC': 0,
         'CountyD': 0},
  'IL': {'CountyM': 0,
         'CountyW': 0,
         'CountyA': 0}
}

print sorted((key, sorted(inner_dict.items())) for key, inner_dict in d.iteritems())