Note that there are some explanatory texts on larger screens.

plurals
  1. POpython list/dict property best practice
    primarykey
    data
    text
    <p>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 <code>id</code> 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:</p> <pre><code>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')]) </code></pre> <p>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:</p> <pre><code>#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) </code></pre> <p>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:</p> <pre><code>#access like a dict print classroom.childrenById['389'] </code></pre> <p>I realize I could just make it a dict, but I want to avoid code like this:</p> <pre><code>classroom.childrendict[child.id] = child </code></pre> <p>I also might have several of these properties, so I don't want to add functions like <code>addChild</code>, 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.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload