【发布时间】:2015-01-05 09:09:45
【问题描述】:
我不确定使用什么函数对程序运行时添加的字典进行排序,字典的格式是 (name:score,name:score .....)
print(" AZ : print out the scores of the selected class alphabteically \n HL : print out the scores of the selected class highest to lowest \n AV : print out the scores of the selected class with there average scores highest to lowest")
choice = input("How would you like the data to be presented? (AZ/HL/AV)")
while True:
if choice.lower() == 'az':
for entry in sorted(diction1.items(), key=lambda t:t[0]):
print(diction1)
break
elif choice.lower()=='hl':
for entry in sorted(diction1.items(), key=lambda t:t[1]):
print(diction1)
break
elif choice.lower() == 'av':
print(diction1)
break
else:
print("invalid entry")
break
【问题讨论】:
-
首先:你的python代码是一堆缩进。没有人能看懂,第二,问题是什么?
-
我使用什么函数对字典进行排序,以便按字母顺序或从高到低读取?
-
Python 的字典是无序的;改用
OrderedDict -
你如何使用它?
-
虽然它们是你的 python 工具包中的一个很棒的工具,但
OrderedDict可能不是这个用例的正确数据结构,因为 a) 你不希望数据井井有条插入,而是以其他几种排序顺序,并且b)您将在进行时添加数据。除非您很少添加并且按请求排序被证明是一个瓶颈,否则最好使用下面的@matthias 解决方案。
标签: python sorting dictionary