gpt4 book ai didi

python - 通过属性以及索引访问递归访问字典?

转载 作者:IT老高 更新时间:2023-10-28 22:20:58 25 4
gpt4 key购买 nike

我希望能够做这样的事情:

from dotDict import dotdictify

life = {'bigBang':
{'stars':
{'planets': []}
}
}

dotdictify(life)

# This would be the regular way:
life['bigBang']['stars']['planets'] = {'earth': {'singleCellLife': {}}}
# But how can we make this work?
life.bigBang.stars.planets.earth = {'singleCellLife': {}}

#Also creating new child objects if none exist, using the following syntax:
life.bigBang.stars.planets.earth.multiCellLife = {'reptiles':{},'mammals':{}}

我的动机是提高代码的简洁性,并尽可能使用与 Javascript 类似的语法来访问 JSON 对象以实现高效的跨平台开发。 (我也使用 Py2JS 和类似的。)

最佳答案

这是创造这种体验的一种方法:

class DotDictify(dict):
MARKER = object()

def __init__(self, value=None):
if value is None:
pass
elif isinstance(value, dict):
for key in value:
self.__setitem__(key, value[key])
else:
raise TypeError('expected dict')

def __setitem__(self, key, value):
if isinstance(value, dict) and not isinstance(value, DotDictify):
value = DotDictify(value)
super(DotDictify, self).__setitem__(key, value)

def __getitem__(self, key):
found = self.get(key, DotDictify.MARKER)
if found is DotDictify.MARKER:
found = DotDictify()
super(DotDictify, self).__setitem__(key, found)
return found

__setattr__, __getattr__ = __setitem__, __getitem__


if __name__ == '__main__':

life = {'bigBang':
{'stars':
{'planets': {} # Value changed from []
}
}
}

life = DotDictify(life)
print(life.bigBang.stars.planets) # -> []
life.bigBang.stars.planets.earth = {'singleCellLife' : {}}
print(life.bigBang.stars.planets) # -> {'earth': {'singleCellLife': {}}}

关于python - 通过属性以及索引访问递归访问字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3031219/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com