问题描述
我正在为我的 GCSE 部分学习,其中要求我打印一个按键字母顺序排序的字典,打印内容应包括相关值.
我花了几个小时试图找到这个问题的答案,并查看了这个论坛上的各种帖子,但对于我有限的知识来说,大多数帖子都太复杂了.
我可以打印按字母顺序排序的键,我可以打印排序的值,但不能打印带有附加值的按字母顺序排序的键.
这是我的简单测试代码
class1 = { 'Ethan':'9','Ian':'3','Helen':'8','Holly':'6' } # 创建字典print(sorted(class1)) # 打印排序的键print(sorted(class1.values())) # 打印排序后的值
我需要打印带值的排序键 - 怎么做?
for k,v in class1.items():print(k,v) # 以我想要的格式打印但不按字母顺序排序
>>>class1 = { 'Ethan':'9','Ian':'3','Helen':'8','Holly':'6' }>>>打印(排序(class1.items()))[('伊桑', '9'), ('海伦', '8'), ('霍莉', '6'), ('伊恩', '3')]
>>>对于 k,v in sorted(class1.items()):... 打印(k,v)...伊森 9海伦 8冬青 6伊恩 3>>>对于 k,v in sorted(class1.items(), key=lambda p:p[1]):...打印(k,v)...伊恩 3冬青 6海伦 8伊森 9>>>对于 k,v in sorted(class1.items(), key=lambda p:p[1], reverse=True):...打印(k,v)...伊森 9海伦 8冬青 6伊恩 3I 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.
This is my simple test code
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 中打印已排序的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!