[英]Accessing elements in arbitarily nested structure of lists / dicts
I have nested structure of python lists and dictionaries. 我有python列表和字典的嵌套结构。
tree = { 'blah': [ "booz", {'foobar': [ { 'somekey': 'someval' } ] } ] }
I also have several recursive functions that allow me to traverse tree
hierarchy from top to bottom and return keys and values that I need. 我还具有几个递归函数,这些函数使我可以从上到下遍历tree
层次结构并返回所需的键和值。 eg.: 例如。:
def get_objectcontent(obj, objid):
result = None
if isinstance(obj, dict):
for key, val in obj.items():
if key == objid:
result = val
elif isinstance(val, list) or isinstance(val, dict):
retval = get_objectcontent(val, objid)
if retval is not None:
result = retval
elif isinstance(obj, list):
for elem in obj:
if isinstance(elem, list) or isinstance(elem, dict):
retval = get_objectcontent(elem, objid)
if retval is not None:
result = retval
return result
Unfortunately, I want to modify the data in tree
too and that is the problem. 不幸的是,我也想修改tree
的数据,这就是问题所在。 Only possible solution that I can see is to construct the 'path' to element dynamically while walking down through the tree
and construct something like: 我看到的唯一可能的解决方案是在遍历tree
同时动态构造元素的“路径”,并构造类似以下内容的东西:
tree['blah'][1]['foobar'][0]['somekey']) = 'newval'
I didn't found any way how could I point to my key in Python (when I know where in structure it is). 我没有找到任何方法可以指向Python中的密钥(当我知道它在结构中的位置时)。
Is there some other, more intelligent way to solve this in Python 3? 在Python 3中还有其他更聪明的方法来解决此问题吗?
You're ultimately looking for objid
as a key in a dict
, so you can change: 您最终将objid
作为dict
的键,因此可以更改:
result = val
to: 至:
result = obj
Then the caller can do: 然后,呼叫者可以执行以下操作:
result[objid] = new_val
You might also consider replacing the assignments to result
with return
statements, assuming you don't mind getting the first instance rather than the last. 您还可以考虑用return
语句替换result
的赋值,假设您不介意获得第一个实例而不是最后一个实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.