0

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)])]
Abid A
  • 7,588
  • 4
  • 32
  • 32
  • 1
    Dictionaries are unordered. You will have to use `OrderedDict` from the`collections` library. – juanpa.arrivillaga Aug 15 '16 at 00:33
  • 1
    What do you want the result to look like? What does your current code give you? Are you aware that dicts are always unsorted? How do you want the data to be stored in the output since dicts are unsorted? – John Zwinck Aug 15 '16 at 00:34
  • @JohnZwinck: I'm expecting something like this: [('IL', [('CountyA', 0), ('CountyM', 0), ('CountyW', 0)]), ('WI', [('CountyC', 0), ('CountyD', 0), ('CountyZ', 0)])] – Abid A Aug 15 '16 at 00:40
  • Similar question: [http://stackoverflow.com/questions/9001509/how-can-i-sort-a-dictionary-by-key](http://stackoverflow.com/questions/9001509/how-can-i-sort-a-dictionary-by-key) – Abhishek Balaji R Aug 15 '16 at 00:41

1 Answers1

1

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())
Karin
  • 8,404
  • 25
  • 34