python3字典升序排序_如何在Python 3.4.3中打印排序的字典

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.

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值