Python 3.4 - Sorting Custom Objects

You can sort objects in a list using the operator module. By creating a class with functions that identify and label the values of your dictionary you can use that info to sort.

from operator import attrgetter

class User:

    def __init__(self, x, y):
        self.name = x
        self.user_id = y

    def __repr__(self):
        return self.name + ":" + str(self.user_id)

users = [
    User('Zach', 38),    User('Mel', 38)
]

for User in users:
    print(User)


for User in sorted(users, key=attrgetter('name')):
    print(User)


https://www.youtube.com/watch?v=fS71qdg5WOY

Comments

Popular posts from this blog

Pyhton 3.4 - Continue

Conversations Ongoing: Valuing Modernization in Early European History

Conversations Ongoing: A Bunch of Amateurs