如何使用Python按排序顺序显示字典中的字典?

2024-06-28 19:37:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本包含字典数据的字典。我试图输出按子字典中的一个值排序的字典(国家)。另外,对年龄进行二次排序是否困难

有人能解释一下这是怎么做到的吗

我的当前代码:

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

Tags: cityage字典updatejohncastevebob
1条回答
网友
1楼 · 发布于 2024-06-28 19:37:55

对于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

对我来说

在Python3.6及更高版本中,可以对字典进行如下排序:

dDict = (dict(sorted(dDict.items(), key=lambda x: x[1]["state"])))

在这里,我在键中输入了lambda x: x[1]["state"],正如您希望按state排序一样。如果您想以其他方式排序,可以更改此项

对于Python2.7,您可以执行以下操作:

from collections import OrderedDict
dDict = OrderedDict(sorted(dDict.items(), key=lambda x: x[1]["state"]))

得到类似的结果

相关问题 更多 >