A dictionary that has a key, the value it is a object of class with attributes
dic = { 1:Person("John, Greenberg", 3),
2:Person("Thomas, San", 5),
3:Person("Annie, Dawn", 7) }
class Person:
def __init__(self, name, total_hour):
self.name = name
self.total_hour = total_hour
How to sort the dictionary by the object's attribute 'name'?
Expected output:
dic = { 3:Person("Annie, Dawn", 7),
1:Person("John, Greenberg", 3),
2:Person("Thomas, San", 5) }
"Sorting" a dictionary and having all its keys be numbers are sort of a "smell" that you're using the wrong data structure -- are you sure you don't want to keep these
Persons in a list rather than a dict?That said, you can "sort" a dict in Python (as of version 3.7) by sorting its
items()and then using the sorted items to recreate a fresh dict, since a dict preserves the insertion order of its keys: