Reputation: 363
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
Upvotes: 3
Views: 64
Reputation: 2114
For python 3.6 and > you can do:
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(dDict)
dDict = (dict(sorted(dDict.items(), key=lambda x: x[1]["state"])))
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"]) )
Prints:
Bob Barker 50 Los Angeles CA
Steve Norton 53 Vulcan CA
Mary Smith 24 Detroit MI
John Doe 27 Salem OR
For me.
In python 3.6 and above, you can sort the dictionary like this:
dDict = (dict(sorted(dDict.items(), key=lambda x: x[1]["state"])))
Here, I entered the lambda x: x[1]["state"]
in the key, as you wanted to sort by state
. You can change this if you want to sort some other way.
For python 2.7, you can do:
from collections import OrderedDict
dDict = OrderedDict(sorted(dDict.items(), key=lambda x: x[1]["state"]))
to get the similar result.
Upvotes: 2