25

I would like to iterate over a dictionary of objects in an attribute sorted way

import operator

class Student:
    def __init__(self, name, grade, age):
        self.name = name
        self.grade = grade
        self.age = age


studi1 = Student('john', 'A', 15)
studi2 = Student('dave', 'B', 10)
studi3 = Student('jane', 'B', 12)

student_Dict = {}
student_Dict[studi1.name] = studi1
student_Dict[studi2.name] = studi2
student_Dict[studi3.name] = studi3

for key in (sorted(student_Dict, key=operator.attrgetter('age'))):
    print(key)

This gives me the error message: AttributeError: 'str' object has no attribute 'age'

Georgy
  • 12,464
  • 7
  • 65
  • 73
Fienchen21
  • 253
  • 1
  • 3
  • 4

4 Answers4

25
for student in (sorted(student_Dict.values(), key=operator.attrgetter('age'))):
    print(student.name)
dugres
  • 12,613
  • 8
  • 46
  • 51
  • 1
    This iterates over the values, sorted by the attribute. This may or may not be what you want; it isn't quite clear in the OP. – Karl Knechtel Apr 07 '12 at 08:39
  • @KarlKnechtel is definitely right that there's some ambiguity in the OP. I believe that this method should be faster than mine, although I do think sorting over the keys is slightly more clear. – Nolen Royalty Apr 07 '12 at 08:46
  • python 2.7 NameError: global name 'operator' is not defined – englishPete Feb 19 '21 at 10:10
11
>>> for key in sorted(student_Dict, key = lambda name: student_Dict[name].age):
...     print key
... 
dave
jane
john
Nolen Royalty
  • 18,415
  • 4
  • 40
  • 50
1
class Student:
    def __init__(self, name, grade, age):
            self.name = name
            self.grade = grade
            self.age = age
    def __repr__(self):
            return repr((self.name, self.grade, self.age))


student_objects = [
    Student('john', 'A', 15),
    Student('jane', 'B', 12),
    Student('dave', 'B', 10),
]
print student_objects
student_objects.sort(key=attrgetter('age'))
print student_objects

source: https://wiki.python.org/moin/HowTo/Sorting

Jry9972
  • 463
  • 7
  • 16
0

How is showed in the documentation of sorted method

sorted(student_Dict.keys(), key=lambda student: student.age)
diegueus9
  • 29,351
  • 16
  • 62
  • 74
  • 4
    You've missed the point. Iterating over a dict iterates over its keys. We are trying to sort the keys according to an attribute of the corresponding value. – Karl Knechtel Apr 07 '12 at 08:37