Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort one inside another

I have a class Person that contains names and hobbies. Then there’s a list that contains people.

  • person1 = Person("MarySmith", ["dancing", "biking", "cooking"])
  • person2 = …
  • people = [person1, person2,..]

I need to return a list of people sorted alphabetically by their name, and also sort their list of hobbies alphabetically.

This is what I have so far:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def sort_people_and_hobbies(people: list) -> list:
    result = []
    for p in people:
        result.append(p)
    return sorted(result, key=lambda x: x.names)

This is what I’m expecting to get:

print(sort_people_and_hobbies(people))  # -> [KateBrown, MarySmith,..]
print(person1.hobbies)  # -> ['biking', 'cooking', 'dancing']

I don’t get how to implement sorting for hobbies into this. No matter what I do I get an unsorted list of hobbies.

>Solution :

You didn’t give the implementation of Person, so it’s hard to give an exact answer. I assume the following.

class Person:
    def __init__(self, name: str, hobbies: list[str]):
        self.name = name
        self.hobbies = hobbies

def sort_people_and_hobbies(people: list[Person]) -> list[Person]:
    for person in people:
        person.hobbies.sort() # we don't have this implementation
                              # so if it's not a dataclass, then modify
    return sorted(people, key = lambda x: x.name)

You could also sort a Person‘s hobbies upon class creation.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading