简体   繁体   English

以对象为键对字典排序

[英]Sort dictionary with Objects as keys

I'm pretty new to python and I'm trying to sort a dict which has some objects as keys. 我是python的新手,我正在尝试对有一些对象作为键的字典进行排序。

I have a class Student(studID, name) which is the key of the dict and an array of grades that is the value of the dict. 我有一个类Student(studID, name) ,它是字典的键,并且是一个分数数组,它是字典的值。

This is what it looks like: 看起来是这样的:

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

That object Student has a method getName() to get the student name. 该对象Student具有方法getName()来获取学生姓名。 What I'm trying to accomplish is to sort this dictionary first by the student name and then by the grades only if the students have the same name. 我要完成的工作是,仅当学生具有相同的姓名时,才按学生姓名对该词典进行排序,然后按年级进行排序。 (if I have two students named Andrew for example) (例如,如果我有两个叫安德鲁的学生)

You have to create an instance of each class in the dictionary: 您必须在字典中创建每个类的实例:

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]))

Output: 输出:

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

Note, however, that dictionaries are unordered, so you will have to rely on a list of tuples, stored in new_dict , or use a collections.OrderedDict : 但是请注意,字典是无序的,因此您将不得不依赖存储在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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM