[英]How do I print a sorted Dictionary in Python 3.4.3
我正在為我的 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
>>> 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
class1 = { 'Ethan':'9','Ian':'3','Helen':'8','Holly':'6' }
class1_keys = class1.keys()
class1_keys.sort()
for i in class1_keys:
print(i,class1[i])
Ethan 9
Helen 8
Holly 6
Ian 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.