【问题标题】:Sort dictionary with Objects as keys以对象为键对字典进行排序
【发布时间】:2017-12-14 15:00:04
【问题描述】:

我对 python 很陌生,我正在尝试对包含一些对象作为键的 dict 进行排序。

我有一个类Student(studID, name),它是字典的键和一个成绩数组,它是字典的值。

这就是它的样子:

dictEx = {
   Student: [5,6],
   Student: [7,8],
   Student: [10,9]
}

那个对象 Student 有一个方法 getName() 来获取学生的名字。我要完成的是首先按学生姓名对这本词典进行排序,然后仅在学生姓名相同时才按成绩排序。 (例如,如果我有两个名叫 Andrew 的学生)

【问题讨论】:

  • 将成绩列表作为学生对象的属性是否更有意义?
  • 那本词典只有一个条目,所以它已经排序了。

标签: python python-3.x python-2.7 dictionary


【解决方案1】:

您必须为字典中的每个类创建一个实例:

class Student:
   def __init__(self, *args):
      self.__dict__ = dict(zip(['name', 'grade'], args))
   def getName(self):
      return self.name
   def __repr__(self):
      return "{}({})".format(self.__class__.__name__, ' '.join('{}:{}'.format(a, b) for a, b in self.__dict__.items()))

dictEx = {
  Student('Tom', 10): [5,6],
  Student('James', 12): [7,8],
  Student('James', 7): [10,9],
}
new_dict = sorted(dictEx.items(), key=lambda x:(x[0].getName(), x[-1]))

输出:

[(Student(grade:12 name:James), [7, 8]), (Student(grade:7 name:James), [10, 9]), (Student(grade:10 name:Tom), [5, 6])]

但请注意,字典是无序的,因此您必须依赖存储在 new_dict 中的元组列表,或使用 collections.OrderedDict

from collections import OrderedDict
d = OrderedDict()
new_dict = sorted(dictEx.items(), key=lambda x:(x[0].getName(), x[-1]))
for a, b in new_dict:
   d[a] = b

【讨论】:

  • new_dicttype 是什么?
  • OrderedDict(sorted(...)) 怎么样?
猜你喜欢
  • 1970-01-01
  • 2015-07-14
  • 2020-10-27
  • 2011-12-11
  • 1970-01-01
  • 2010-11-15
  • 1970-01-01
  • 2021-02-12
  • 2018-12-22
相关资源
最近更新 更多