【问题标题】:Im not sure what functions to use when sorting a dictionary我不确定在对字典进行排序时要使用哪些功能
【发布时间】: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


【解决方案1】:

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 不是一个选项,因为您不想保持顺序,而是想使用不同的标准进行排序。

【讨论】:

  • 这很奇怪。我从 Python 控制台复制了代码和结果。
猜你喜欢
  • 2015-11-01
  • 1970-01-01
  • 2018-08-26
  • 2012-10-06
  • 2011-06-09
  • 1970-01-01
  • 1970-01-01
  • 2020-08-15
  • 2021-08-26
相关资源
最近更新 更多