Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,102 questions

55,976 answers

573 users

How to sort a list of classes that contain nested classes using custom comparison logic in Python

1 Answer

0 votes
from dataclasses import dataclass
 
# ------------------------------------------------------------
# Example: Sorting a list of user-defined structs (classes)
# that contain nested structs
# ------------------------------------------------------------
 
# A nested struct representing an address
@dataclass
class Address:
    city: str
    zip: int
 
# A struct representing a person, containing a nested Address
@dataclass
class Person:
    name: str
    age: int
    address: Address
 
# ------------------------------------------------------------
# Helper function to print the list
# ------------------------------------------------------------
def print_persons(people):
    for p in people:
        print(f"{p.name} | age: {p.age} | city: {p.address.city} | zip: {p.address.zip}")
 
# ------------------------------------------------------------
# Main program
# ------------------------------------------------------------
people = [
    Person("Alice", 30, Address("San Francisco", 42100)),
    Person("Bob",   40, Address("Austin",        32000)),
    Person("Carol", 35, Address("New York City", 42000)),
    Person("Dave",  35, Address("Austin",        32000)),
    Person("Eve",   28, Address("New York City", 61000)),
]
 
# ------------------------------------------------------------
# Sort using sorted():
#   1. city
#   2. zip
#   3. age
# ------------------------------------------------------------
sorted_people = sorted(
    people,
    key=lambda p: (p.address.city, p.address.zip, p.age)
)
 
# Print the sorted result
print_persons(sorted_people)
 
 
'''
run:
 
Dave | age: 35 | city: Austin | zip: 32000
Bob | age: 40 | city: Austin | zip: 32000
Carol | age: 35 | city: New York City | zip: 42000
Eve | age: 28 | city: New York City | zip: 61000
Alice | age: 30 | city: San Francisco | zip: 42100

'''

 



answered Sep 1 by avibootz
edited Sep 1 by avibootz

Related questions

...