2

Having the following subclass of dict, I need to override the items() and values() methods in such a way that they would return ValuesView[tuple] and ItemsView[str, tuple]

Here the class I'm coding:

from typing import ItemsView

VALUES = "VALUES"
OPERATORS = "OPERATORS"

class Query(dict):
    def __init__(self, operators: dict = {}, values: dict = {}) -> None:
        super().__init__()

        if not operators.keys() == values.keys():
            raise Exception("Keys of operators and values must be the same!!!")

        self[OPERATORS]: dict[str, str] = operators
        self[VALUES]: dict[str, int | float | str | list] = values

    def get_fields(self) -> list:
        return self[OPERATORS].keys()

    def get_operators(self) -> dict:
        return self[OPERATORS]

    def get_values(self) -> dict:
        return self[VALUES]

    def __getitem__(self, k: str) -> dict or tuple:
        try:
            return super().__getitem__(k)
        except KeyError:
            operator = self.get_operators()[k]
            value = self.get_operators()[k]

            return operator, value

    def keys(self) -> KeysView[str]:
        return self[OPERATORS].keys()

    def values(self) -> ValuesView[tuple]:
        # Here I should return tuples (self[OPERATORS][key], self[VALUES][key]
        # return super().values()    

    def items(self) -> ItemsView[str, tuple]:
        # return super().items()

How can I build such views?

UPDATE

As a temporary solution, I'm using List comprehensions, which get the job done, however not at 100%. Of course I would like to know the appropriate way to build these views, since they are different from lists.

enter image description here

def values(self) -> ValuesView[tuple]:
    return [(self[OPERATORS][key], self[VALUES][key]) for key in self.keys()]

def items(self) -> ItemsView[str, tuple]:
    return [(key, (self[OPERATORS][key], self[VALUES][key])) for key in self.keys()]
1Z10
  • 2,801
  • 7
  • 33
  • 82

0 Answers0