问题
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
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.
See: Store Slice Index as Object.
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.
Edit: It would also be nice to be able to change values in the original object using the key:
ExampleObject3[ (0,'b',0,'b') ] = 'alpha'
回答1:
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
Edit based on further information
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
来源:https://stackoverflow.com/questions/64419760/access-jsonable-nested-object-with-comma-separated-key