Skip to content

nested dict access via a pathing system #117

Open
@RitikShah

Description

aka: being able to access a nested item via an xpath-esque syntax

>>> from addict import Dict
>>> a = Dict()
>>> a.b.c = 10
>>> a.b.d = 20
>>> a.c.c = 100
>>> a.c.d = 200
>>>
>>> a.search('a/b/c')  # or a.search('a.b.c')
10
>>> a.search('a/b').c = 11
>>> a.b.c
11
>>> a.search('a/b/[cd]')
(11, 20)
>>> a.search('a/b/[cd]', full_path=True)
{a: {b: {c: 11, d: 20}}}
>>> a.search('a/*/c', full_path=True)
{a: {b: {c: 11}, c: {c: 100}}

There's a lot more that could be expanded upon this. This is basically like the dpath library or the jsonpointer library but integrated into the library.

I think this is a good opportunity for a kind of superdict as this as it implements a lot of possibilities. It could be as simple as binding the dpath functions internally making that lib a requirement (eh), or maybe creating an interface akin to that.

However, I realize this is a lot to request (hehe) and probably is more work than warranted (I could try to take a stab at it potentially). Another less extreme idea is just to add simple iterable get and set.
ex:

>>> from addict import Dict
>>> a = Dict()
>>> a.b.c = 10
>>> a.get_from(['a', 'b', 'c'])
10
>>> a.set_from(['a', 'b', 'c'], 20)
>>> a.b.c
20
>>> # this functionality can easily be replicated but it uses eval so it's not favorable
>>> path = '.'.join(['a', 'b', 'c'])
>>> eval(f'a.{path}')  # yuck
20

These are just a couple ideas I had. I think the first idea might be taking it a lil too far but the latter does fit in with the rest of this class I feel. Just wondering what you thought. I potentially may come with a pull request if I find the time.

Thanks!
~ Ritik Shah ~

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions