-1

Want to access a dict via a String like dict[accessor] while acccessor is 'keyA.nestedKeyB'. Found something here with Lambda and overwriting the dict class ( https://stackoverflow.com/questions/39818669/dynamically-accessing-nested-dictionary-keys ) but unfortunetly there is no working example.

Code

data = { "keyA": { "nestedKeyB": "Hello" } }

print(data['keyA']['nestedKeyB'])  # prints 'Hello'

accessor = 'keyA.nestedKeyB'
print(data[accessor])  # KeyError
Dirk Schiller
  • 491
  • 6
  • 18
  • You cannot do this with a `dict`. You could write your own class that does this, but why? Why not just use the regular way? You can even very trivially use `'keyA.nestedKeyB'` to generate the keys using `'keyA.nestedKeyB'.split('.')` Note, you can't "overwrite" the dict class, and even if you could you really shouldn't – juanpa.arrivillaga May 14 '20 at 00:14
  • @jizhihaoSAMA: My fault. Corrected it. – Dirk Schiller May 14 '20 at 00:14
  • @juanpa.arrivillaga: The dict can have different nested levels. For that reason my `accessor` could have different amount of keys. Because of that I need a way to access each level by the `accessor`. I do not understand your `split` example. – Dirk Schiller May 14 '20 at 00:17
  • 1
    So what? Again, just *split* the accessors then loop over them and access, essentially like the answers in the question you already linked to... – juanpa.arrivillaga May 14 '20 at 00:18
  • @juanpa.arrivillaga: You are right. Thank you! – Dirk Schiller May 14 '20 at 00:22

2 Answers2

2

Since python dict doesn't support dot notations, you will have to convert the accessor to foo["bar"]["baz"] form.

Something as simple as,

def access(foo, accessor):
    keys = accessor.split('.')
    data = foo
    for key in keys:
        data = data[key]
    return data
dumbPy
  • 1,379
  • 1
  • 6
  • 19
0
import jsonpath
import json #in this sample, don't need import this.
data = { "keyA": { "nestedKeyB": "Hello" } }
node = jsonpath.jsonpath(data, "$.keyA.nestedKeyB")
print(node) # if node is not False, it's a list
print (node == False) # not found match result by this jsonpath? Then node == False

recommend you to use jsonpath library and JSONPath expression. You can work with more complex json data

Zhd Zilin
  • 143
  • 7