0

Could anyone please help with a proper solution for this minimalistic example? I would like to iterate through a dictionary field of the class:

class MyClass:

    _a_dic : dict

    def __init__(self, a_dic : dict = None):
        if a_dic:
            self._a_dic = a_dic
        else:
            self._a_dic = {}

    @property
    def a_dic( self ):
        return self._a_dic

    def __iter__(self):
        ???

    def __next__(self):
        ???

bruh = MyClass( {'one' : 1, 'two' : 2} )

print( [ t for t in bruh ] )
> ['one', 'two']

print( [ bruh[t] for t in bruh ] )
> [1, 2]

I would also like to learn how this would work if I used a list instead of the dictionary.

mavzolej
  • 200
  • 2
  • 8

1 Answers1

1

Just implement __iter__ to delegate to that dict,

class MyClass:

    _a_dic : dict

    def __init__(self, a_dic : dict = None):
        if a_dic:
            self._a_dic = a_dic
        else:
            self._a_dic = {}
    
    def __iter__(self):
        return iter(self._a_dic)
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172