我有一本包含字典数据的字典。我正在尝试输出按子词典中的值之一排序的词典。 (国家)。另外,对年龄进行二次排序会不会很困难?
谁能解释一下这是怎么做到的?
我当前的代码:
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"]) )
输出:
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
我想要什么:
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
最佳答案
对于 python 3.6 和 > 你可以这样做:
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"]) )
打印:
Bob Barker 50 Los Angeles CA
Steve Norton 53 Vulcan CA
Mary Smith 24 Detroit MI
John Doe 27 Salem OR
对我来说。
在python 3.6及以上版本中,你可以这样对字典进行排序:
dDict = (dict(sorted(dDict.items(), key=lambda x: x[1]["state"])))
在这里,我在键中输入了 lambda x: x[1]["state"]
,因为您想按 state
排序。如果您想以其他方式排序,可以更改此设置。
对于python 2.7,你可以这样做:
from collections import OrderedDict
dDict = OrderedDict(sorted(dDict.items(), key=lambda x: x[1]["state"]))
得到相似的结果。
关于python - 如何使用 Python 按排序顺序显示字典中的字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55958765/