简体   繁体   English

检索 class 实例中的嵌套字典

[英]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 Toe s.现在我想查看Shoe实例内部并检索/更新所有绿色和blue ToeSock实例。 Then update the Sock / Toe instances I retrieved so that when I access the shoe later the values have changed.然后更新我检索到的Sock / Toe实例,这样当我稍后访问鞋子时,值已经改变。

All help is appreciated!感谢所有帮助!

I suggest that you can use a list instead of obj我建议您可以使用列表而不是 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问候

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM