I have a dictionary that contains dictionary data. I am trying to output the dictionary sorted by one of the values in the sub-dictionary. (the State). Also, would it be difficult to perform a secondary sort on the age?
Can someone explain how this is done?
My current code:
dDict = {}
dDict.update( { "Bob Barker": {"age":50, "city":"Los Angeles", "state":"CA" } } )
dDict.update( { "Steve Norton": {"age":53, "city":"Vulcan", "state":"CA" } } )
dDict.update( { "John Doe": {"age":27, "city":"Salem", "state":"OR" } } )
dDict.update( { "Mary Smith": {"age":24, "city":"Detroit", "state":"MI" } } )
print("Name Age City State")
for d in dDict:
print ("{:12} {:3} {:11} {:2}".format(d, dDict[d]["age"], dDict[d]["city"], dDict[d]["state"]) )
Output:
Name Age City State
Steve Norton 53 Vulcan CA
Mary Smith 24 Detroit MI
Bob Barker 50 Los Angeles CA
John Doe 27 Salem OR
What I would like:
Name Age City State
Bob Barker 50 Los Angeles CA
Steve Norton 53 Vulcan CA
Mary Smith 24 Detroit MI
John Doe 27 Salem OR