我不知道在给字典排序时使用什么函数

2024-04-16 20:37:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我不知道用什么函数来排序一个字典,当程序运行时,字典的格式是(名称: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

Tags: oftheto名称字典outlowerclass
1条回答
网友
1楼 · 发布于 2024-04-16 20:37:16

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

使用^{}在这里不是一个选项,因为您不想保持顺序,而是想用不同的条件排序。你知道吗

相关问题 更多 >