我不确定在排序字典时要使用哪些函数

时间:2015-01-05 09:09:45

标签: python sorting dictionary

我不确定用什么函数来排序在程序运行时添加的字典,字典的格式是(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

1 个答案:

答案 0 :(得分:2)

dictionary无序。

您可以对输出数据进行排序。

>>> data = {'b': 2, 'a': 3, 'c': 1}
>>> for key, value in sorted(data.items(), key=lambda x: x[0]):
...     print('{}: {}'.format(key, value))
...     
a: 3
b: 2
c: 1
>>> for key, value in sorted(data.items(), key=lambda x: x[1]):
...     print('{}: {}'.format(key, value))
...     
c: 1
b: 2
a: 3

此处不能使用OrderedDict,因为您不想维护订单,但希望按不同的标准排序。

相关问题