Reputation: 2363
I have several classes which have dictionaries as attributes. These dictionaries store instances of other classes. The lower/nested classes also have dictionaries as attributes as well.
Currently I am writing full loops, with breaks, to retrieve the nested values. Problem is that I need to do several processes/filters on the nested dictionaries so it seems computationally expensive as well as it leading to ugly, spaghetti-like code. What I would like to do is be able to access the nested items, update the items (in-place), and continue on.. Is there a way to do this?
Example code (let's assume you might wear several socks in each shoe and have several colored toes):
class Shoe:
def __init__(self):
self.socks = {} # this contains instances of socks
class Sock:
def __init__(self):
self.toes = {} # this contains instances of toes
self.color = 'green'
class Toe:
def __init__(self):
self.color = 'blue'
Now I want to look inside the Shoe
instance and retrieve/update all Sock
instances which are green and have blue
Toe
s. Then update the Sock
/Toe
instances I retrieved so that when I access the shoe later the values have changed.
All help is appreciated!
Upvotes: 0
Views: 34
Reputation: 1129
I suggest that you can use a list instead of obj
class Shoe:
def __init__(self):
self.socks = [] # this contains instances of socks
class Sock:
def __init__(self):
self.toes = [] # this contains instances of toes
self.color = 'green'
class Toe:
def __init__(self):
self.color = 'blue'
toe = Toe()
socks = Sock()
socks.toes.append(toe)
shoes = Shoe()
shoes.socks.append(socks)
then you can iterate as you want
for s in shoes.socks: # s becomes in a list of sock
for t in s.toes: # t becomes in a list of toes
for color in t:
print(color)
or maybe i do not understand what you really need.
greeting
Upvotes: 1