如何在Python3.4.3中打印排序字典

2024-05-29 10:18:20 发布

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

我正在为我的GCSE部分学习,其中要求我打印一本字典,按字母顺序排序的关键和打印应包括相关的价值。

我花了几个小时试图找到这个问题的答案,并查看了这个论坛上的各种帖子,但大多数都太复杂,我的知识有限。

我可以打印按字母顺序排序的键,也可以打印已排序的值,但不能打印附加值的按字母顺序排序的键。

这是我的简单测试代码

class1 = { 'Ethan':'9','Ian':'3','Helen':'8','Holly':'6' } # create dictionary

print(sorted(class1)) # prints sorted Keys
print(sorted(class1.values())) # Prints sorted values

我需要打印有值的排序键-怎么做?

for k,v in class1.items():
    print(k,v)  # prints out in the format I want but not alphabetically sorted

Tags: 答案in字典排序顺序字母prints关键
1条回答
网友
1楼 · 发布于 2024-05-29 10:18:20
>>> class1 = { 'Ethan':'9','Ian':'3','Helen':'8','Holly':'6' }
>>> print(sorted(class1.items()))
[('Ethan', '9'), ('Helen', '8'), ('Holly', '6'), ('Ian', '3')]

>>> for k,v in sorted(class1.items()):
...     print(k, v)
...
Ethan 9
Helen 8
Holly 6
Ian 3

>>> for k,v in sorted(class1.items(), key=lambda p:p[1]):
...     print(k,v)
...
Ian 3
Holly 6
Helen 8
Ethan 9

>>> for k,v in sorted(class1.items(), key=lambda p:p[1], reverse=True):
...     print(k,v)
...
Ethan 9
Helen 8
Holly 6
Ian 3

相关问题 更多 >

    热门问题