使用逗号分隔键访问jsonable嵌套对象 [英] Access jsonable nested object with comma separated key
问题描述
首先让我们创建一个可在python中jsonable的嵌套对象:
First lets create a nested object which is jsonable in python:
ExampleObject1 = [ {'a':0, 'b':1} , {'c':2, 'd':3} ]
ExampleObject2 = [ {'a':0, 'b':ExampleObject1}, {'c':2, 'd':3} ]
ExampleObject3 = [ {'a':0, 'b':ExampleObject1}, {'c':ExampleObject2, 'd':3} ]
我们可以像这样通过链接方括号轻松访问元素:
We can easily access an element with chaining square brackets like so:
print ( ExampleObject3[0]['b'][0]['b'] )
>>> 1
如何使用键列表访问同一元素,而不需要方括号?
How can I access the same element with a list of keys instead of needing the square brackets?
print ( ExampleObject3[ (0,'b',0,'b') ] )
>>> TypeError: list indices must be integers or slices, not tuple
注意:我可以这样访问numpy
array
.
一旦我尝试用逗号分隔的键访问字典,事情就会中断.
Note: I can access numpy
array
s this way.
As soon as I try to access a dictionary with comma separated key's then things break.
请参阅:将切片索引存储为对象.
原因:我只希望能够传递一个任意密钥,该密钥可用于以后从内存中的某个大对象获取数据.
Reason: I just want to be able to pass around an arbitrary key which can be used to go get data later from some large object sitting in memory.
使用键可以在原始对象中更改值也很好:
It would also be nice to be able to change values in the original object using the key:
ExampleObject3[ (0,'b',0,'b') ] = 'alpha'
推荐答案
您不能直接使用像这样的键列表建立索引,但是您可以创建一个简单的函数来为您完成此操作. functools.reduce()
对此很方便:
You can't index directly with a list of key like this, but you could make a simple function to do it for you. functools.reduce()
is handy for this:
from functools import reduce
def fromKeyList(obj, key_list):
return reduce(lambda o, k: o[k], key_list, obj)
ExampleObject1 = [ {'a':0, 'b':1} , {'c':2, 'd':3} ]
ExampleObject2 = [ {'a':0, 'b':ExampleObject1} , {'c':2, 'd':3} ]
ExampleObject3 = [ {'a':0, 'b':ExampleObject1} , {'c':ExampleObject2, 'd':3} ]
fromKeyList(ExampleObject3, (0,'b',0,'b'))
# 1
fromKeyList(ExampleObject3, (1,'c',0,'b',1, 'c'))
# 2
根据更多信息进行编辑
要设置一个项目,您可以从密钥列表中获取除最后一个项目以外的所有项目,然后使用最后一个密钥来设置该项目.看起来可能像这样:
To set an item, you can get all but the last item from the key list, then use the last key to set the item. That might look something like:
def setFromKeyList(obj, key_list, val):
last = reduce(lambda o, k: o[k], key_list[:-1], obj)
last[key_list[-1]] = val
fromKeyList(ExampleObject3, (0,'b',0,'b'))
# 1
setFromKeyList(ExampleObject3, (0,'b',0,'b'), 10)
fromKeyList(ExampleObject3, (0,'b',0,'b'))
#10
这篇关于使用逗号分隔键访问jsonable嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!