How to sort dictionaries of objects by attribute value?
33,143
Solution 1
for student in (sorted(student_Dict.values(), key=operator.attrgetter('age'))):
print(student.name)
Solution 2
>>> for key in sorted(student_Dict, key = lambda name: student_Dict[name].age):
... print key
...
dave
jane
john
Related videos on Youtube
Author by
Fienchen21
Updated on July 01, 2020Comments
-
Fienchen21 almost 4 years
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'
-
Karl Knechtel about 12 yearsYou'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 about 12 yearsThis iterates over the keys, according to the corresponding value's attribute. This may or may not be what you want; it isn't quite clear in the OP.
-
Karl Knechtel about 12 yearsThis 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.
-
Nolen Royalty about 12 years@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.
-
martineau about 12 years@Karl: I think this is what the OP's looking for based on what they wrote.
-
englishPete about 3 yearspython 2.7 NameError: global name 'operator' is not defined