Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4085138
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T18:31:59+00:00 2026-05-20T18:31:59+00:00

I have a class object that stores some properties that are lists of other

  • 0

I have a class object that stores some properties that are lists of other objects. Each of the items in the list has an identifier that can be accessed with the id property. I’d like to be able to read and write from these lists but also be able to access a dictionary keyed by their identifier. Let me illustrate with an example:

class Child(object):
    def __init__(self, id, name):
        self.id = id
        self.name = name

class Teacher(object):
    def __init__(self, id, name):
        self.id = id
        self.name = name

class Classroom(object):
    def __init__(self, children, teachers):
        self.children = children
        self.teachers = teachers

classroom = Classroom([Child('389','pete')],
                      [Teacher('829','bob')])

This is a silly example, but it illustrates what I’m trying to do. I’d like to be able to interact with the classroom object like this:

#access like a list
print classroom.children[0]
#append like it's a list
classroom.children.append(Child('2344','joe'))
#delete from like it's a list
classroom.children.pop(0)

But I’d also like to be able to access it like it’s a dictionary, and the dictionary should be automatically updated when I modify the list:

#access like a dict
print classroom.childrenById['389']

I realize I could just make it a dict, but I want to avoid code like this:

classroom.childrendict[child.id] = child

I also might have several of these properties, so I don’t want to add functions like addChild, which feels very un-pythonic anyway. Is there a way to somehow subclass dict and/or list and provide all of these functions easily with my class’s properties? I’d also like to avoid as much code as possible.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T18:32:00+00:00Added an answer on May 20, 2026 at 6:32 pm

    An indexed list class:

    class IndexedList(list):
        def __init__(self, items, attrs):
            super(IndexedList,self).__init__(items)
            # do indexing
            self._attrs = tuple(attrs)
            self._index = {}
            _add = self._addindex
            for obj in self:
                _add(obj)
    
        def _addindex(self, obj):
            _idx = self._index
            for attr in self._attrs:
                _idx[getattr(obj, attr)] = obj
    
        def _delindex(self, obj):
            _idx = self._index
            for attr in self._attrs:
                try:
                    del _idx[getattr(obj,attr)]
                except KeyError:
                    pass
    
        def __delitem__(self, ind):
            try:
                obj = list.__getitem__(self, ind)
            except (IndexError, TypeError):
                obj = self._index[ind]
                ind = list.index(self, obj)
            self._delindex(obj)
            return list.__delitem__(self, ind)
    
        def __delslice__(self, i, j):
            for ind in xrange(i,j):
                self.__delitem__(ind)
    
        def __getitem__(self, ind):
            try:
                return self._index[ind]
            except KeyError:
                return list.__getitem__(self, ind)
    
        def __getslice__(self, i, j):            
            return IndexedList(list.__getslice__(self, i, j))
    
        def __setitem__(self, ind, new_obj):
            try:
                obj = list.__getitem__(self, ind)
            except (IndexError, TypeError):
                obj = self._index[ind]
                ind = list.index(self, obj)
            self._delindex(obj)
            self._addindex(new_obj)
            return list.__setitem__(ind, new_obj)
    
        def __setslice__(self, i, j, newItems):
            _get = self.__getitem__
            _add = self._addindex
            _del = self._delindex
            newItems = list(newItems)
            # remove indexing of items to remove
            for ind in xrange(i,j):
                _del(_get(ind))
            # add new indexing
            if isinstance(newList, IndexedList):
                self._index.update(newList._index)
            else:
                for obj in newList:
                    _add(obj)
            # replace items
            return list.__setslice__(self, i, j, newList)
    
        def append(self, obj):
            self._addindex(obj)
            return list.append(self, obj)
    
        def extend(self, newList):
            newList = list(newList)
            if isinstance(newList, IndexedList):
                self._index.update(newList._index)
            else:
                _add = self._addindex
                for obj in newList:
                    _add(obj)
            return list.extend(self, newList)
    
        def insert(self, ind, new_obj):
            # ensure that ind is a numeric index
            try:
                obj = list.__getitem__(self, ind)
            except (IndexError, TypeError):
                obj = self._index[ind]
                ind = list.index(self, obj)
            self._addindex(new_obj)
            return list.insert(self, ind, new_obj)
    
        def pop(self, ind=-1):
            # ensure that ind is a numeric index
            try:
                obj = list.__getitem__(self, ind)
            except (IndexError, TypeError):
                obj = self._index[ind]
                ind = list.index(self, obj)
            self._delindex(obj)
            return list.pop(self, ind)
    
        def remove(self, ind_or_obj):
            try:
                obj = self._index[ind_or_obj]
                ind = list.index(self, obj)
            except KeyError:
                ind = list.index(self, ind_or_obj)
                obj = list.__getitem__(self, ind)
            self._delindex(obj)
            return list.remove(self, ind)
    

    which can be used as:

    class Child(object):
        def __init__(self, id, name):
            self.id = id
            self.name = name
    
    class Teacher(object):
        def __init__(self, id, name):
            self.id = id
            self.name = name
    
    class Classroom(object):
        def __init__(self, children, teachers):
            self.children = IndexedList(children, ('id','name'))
            self.teachers = IndexedList(teachers, ('id','name'))
    
    classroom = Classroom([Child('389','pete')], [Teacher('829','bob')])
    
    print classroom.children[0].name               # -> pete
    
    classroom.children.append(Child('2344','joe'))
    print len(classroom.children)                  # -> 2
    print classroom.children[1].name               # -> joe
    print classroom.children['joe'].id             # -> 2344
    print classroom.children['2344'].name          # -> joe
    
    p = classroom.children.pop('pete')
    print p.name                                   # -> pete
    print len(classroom.children)                  # -> 1
    

    Edit: I had made a mistake in some of the exception-handling (catching KeyError instead of IndexError); it is fixed. I will add some unit-testing code. If you run into any further errors, please let me know!

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a Python class that stores some fields and has some properties, like
Assume I have a business object that has some properties that should be read-only.
I have an object that has a few different List properties that contain child
I have a list of class object that I created as a variable in
I have a settings class, which has some properties for usability and to restrict
We have the Class object (an object that reference a Class) so you can
I have an Employee class object that I am calling from my Login.aspx page's
Assume that I have a particular class of object that defines a class method
I want to create a Javascript class/object that allow me to have various method:
I have a class that spawns an arbitrary number of worker object that compute

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.