Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

python - Retrieving nested dictionaries in class instances

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 Toes. Then update the Sock/Toe instances I retrieved so that when I access the shoe later the values have changed.

All help is appreciated!

question from:https://stackoverflow.com/questions/65850518/retrieving-nested-dictionaries-in-class-instances

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...