ezgibec
ezgibec

Reputation: 19

How do I use tuples as key for __setitem__

I'm trying to assign values to my nested list using the setitems method. However, since Python only allows one key in setitems, I'm having some trouble.

class Place:
    def __init__(self, x: int, y: int):
        self.x = x
        self.y = y

class ABC(Place):
    def __init__(self):
        self.nestedlist = [["", "", ""], ["", "", ""], ["", "", ""]]
    def __setitem__(self, key, value):
        self.nestedlist[[x][y]] = value

My place class defines the index of my value within the nested list & it's mandatory to be used for my task. What I want to do is:

Input:

myobject = ABC()
myplace = Place(0,2)
myobject[myplace] = 9

Output:

nestedlist = [["", "", 9], ["", "", ""], ["", "", ""]]

Upvotes: 0

Views: 180

Answers (1)

Samwise
Samwise

Reputation: 71444

from dataclasses import dataclass

@dataclass
class Place:
    x: int
    y: int


class ABC:
    def __init__(self) -> None:
        self.nestedlist: list[list[str|int]] = [
            [""] * 3 for _ in range(3)
        ]

    def __setitem__(self, key: Place, value: int) -> None:
        self.nestedlist[key.x][key.y] = value
    
    def __str__(self) -> str:
        return str(self.nestedlist)


myobject = ABC()
myplace = Place(0,2)
myobject[myplace] = 9
print(myobject)
# [['', '', 9], ['', '', ''], ['', '', '']]

Note:

  • The critical things you were missing were to access the x and y attributes of your key argument (which is a Place), and to do nested lookups on your nested list with them.
  • Place is not a tuple. (I made it a dataclass, which behaves exactly the same as your original code but is an easier way to write it since you don't need to write each attribute twice the way you do in a manually written __init__ where each attribute is also a parameter.)
  • It doesn't make sense for ABC to be a type of (inherit from) Place, since an ABC actually represents many Places.

Upvotes: 2

Related Questions