如何在Python 3.4.3中打印排序的字典 [英] How do I print a sorted Dictionary in Python 3.4.3

查看:172
本文介绍了如何在Python 3.4.3中打印排序的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究我的GCSE,其中的一部分要求我打印按字母顺序排序的字典,并且打印内容应包含相关值.

I am studying for my GCSE part of which requires me to print a dictionary sorted alphabetically by key and the print should include the associated value.

我花了数小时试图找到答案,并看了这个论坛上的各种帖子,但是对于我的有限知识,大多数帖子太过复杂了.

I have spent hours trying to find the answer to this and have looked at various posts on this forum but most are too complex for my limited knowledge.

我可以打印按字母顺序排序的键,也可以打印排序后的值,但不能打印按字母顺序排序的键(带有附加值).

I can print alphabeticallycsorted Keys and I can print sorted values but not alphabetically sorted keys with the values attached.

这是我的简单测试代码

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

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

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

I need to print sorted keys with values - how to do that?

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

推荐答案

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

这篇关于如何在Python 3.4.3中打印排序的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆