GonzaloXavier GonzaloXavier - 1 year ago 81
Python Question

Python sort a dictionary that has classes in it's values by alphabetical order of one of it's attributes

so I'm making an agenda.

The attribute of agenda that manages the dictionary is : self.ContactList = {}

Inside this I have the telephone number as key for a contact (which is a class).

The Contact class has an attribute called telephone and other ones including the contact name.

I want a function that lists the contacts in the agenda, however I wanna list them by alphabetical order of the Contacts it contains.

Right now I'm using this to print the contacts (already have overriden the ____str____ of the contact class to allow this):

def listcontacts(self, agenda):
print("Contact List\n")
for tel, contact in agenda.ContactList.items():

How to sort self.ContactList by the contact's attribute "name"?

EDIT: The contact class is as follows

class Contact:
def __init__(self, name, adress, zipcode, telephone):
self.name = name
self.adress = adress
self.zipcode = zipcode
self.telephone = telephone
def __str__(self):
return ( "Name: " + self.name + "\nAdress: " + self.adress + "\nZipCode: " + self.zipcode
+ "\nTelephone: " + self.telephone)

Answer Source

If you want to sort a list, use the sorted() function. If you want the sort to use an interesting ordering criterion, use the key= keyword:

for tel, contact in sorted(agenda.ContactList.items(), key=lambda x: x[1].name):
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download