Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort dictionaries of objects by attribute value?

Tags:

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'

like image 959
Fienchen21 Avatar asked Apr 07 '12 08:04

Fienchen21


People also ask

How do you sort a dictionary based on a value?

First, we use the sorted() function to order the values of the dictionary. We then loop through the sorted values, finding the keys for each value. We add these keys-value pairs in the sorted order into a new dictionary. Note: Sorting does not allow you to re-order the dictionary in-place.

Can we sort the dictionary based on values in Python?

Older PythonIt is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples.

How do you sort a dictionary in descending order based on values?

Use dict. items() to get a list of tuple pairs from d and sort it using a lambda function and sorted(). Use dict() to convert the sorted list back to a dictionary. Use the reverse parameter in sorted() to sort the dictionary in reverse order, based on the second argument.


1 Answers

for student in (sorted(student_Dict.values(), key=operator.attrgetter('age'))):     print(student.name) 
like image 170
dugres Avatar answered Oct 16 '22 08:10

dugres