使用对象作为键

时间:2017-12-14 15:00:05

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

我对python很陌生,我试图对一个有一些对象作为键的dict进行排序。

我有一个类Student(studID, name),它是dict的关键,是一个等级数组,是dict的值。

这就是它的样子:

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

该对象Student有一个方法getName()来获取学生姓名。我想要完成的是首先按学生姓名对该词典进行排序,然后仅在学生名称相同的情况下按等级排序。 (例如我有两个名叫安德鲁的学生)

1 个答案:

答案 0 :(得分:4)

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

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
相关问题