0

I'm looking for the best way to go about subscripting a multi-layer Python dict with a string containing forward slashes to indicate sub keys. Currently I have something like this:

>>> data = {'some': {'key': 'value'}, 'foo': {'bar': 'pow'}}  # data received from an external api
>>> field = 'some/key'  # metadata path received from the same api
>>> for key in field.split('/'):
...     data = data.get(key)
... print(data)
value
martineau
  • 119,623
  • 25
  • 170
  • 301
Dillon Miller
  • 763
  • 1
  • 6
  • 18
  • If you could use nested objects instead of nested dictionaries, then you could use `.` and access the objects’s properties directly. Then even consider [`eval()`](https://docs.python.org/3/library/functions.html#eval) (careful with that function, though)… – Jens Jun 10 '20 at 23:47
  • The dict object I receive is from an external source. The one I posted above is just an example. – Dillon Miller Jun 10 '20 at 23:48
  • Then consider wrapping the dictionary into an “object view”, something like [this blog](https://goodcode.io/articles/python-dict-object/) describes. – Jens Jun 10 '20 at 23:49
  • 1
    I would bind the dictionary to a second name and use that in your loop, so that `data` is still the same after accessing the element. Otherwise the solution lokks fine. – Matthias Jun 10 '20 at 23:53
  • 1
    There's no point switching from dicts to something that uses attribute access notation. It just means you end up using `getattr` instead of indexing, and that's no improvement. (That, or you end up with `eval`, which has far too many failure cases to suggest using, and puts a major security hole in your code for no benefit.) – user2357112 Jun 10 '20 at 23:53
  • 2
    Is there a reason not to just wrap your current logic in a function and use it? – Blckknght Jun 11 '20 at 00:01
  • I can use a function, I was wondering if there was a more straightforward approach to this. – Dillon Miller Jun 11 '20 at 00:07
  • Is the use of forward slashes written in stone? If not, then there may be something you can do with jmespath. – Rory Browne Jun 10 '20 at 23:48
  • Yes, it's included in metadata I'm receiving from an external api. – Dillon Miller Jun 10 '20 at 23:49
  • The data-structure described and the answers to the question [What is the best way to implement nested dictionaries?](https://stackoverflow.com/questions/635483/what-is-the-best-way-to-implement-nested-dictionaries) might help. – martineau Jun 11 '20 at 01:40

0 Answers0