Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support returning indexes of list value in keypaths() utility function #13

Closed
momocow opened this issue Mar 26, 2020 · 2 comments
Closed
Assignees
Labels
enhancement New feature or request

Comments

@momocow
Copy link

momocow commented Mar 26, 2020

For example,

data = {"items": ["a", {"c": 1}]}

assert benedict(data).keypaths() == [
    "items",
    "items[0]",
    "items[1]",
    "items[1].c"
]

In my use case, I have a regular expression as a filter for keypaths, the filtered keypaths are passed to subset() to make a new filtered dict.

For example,

import re

filter = "items[\d+].name"

data = {"items": [{"name": "a", "value": "b"}, {"name": "c", "value": "d"}]}
b_data = benedict(data)


filtered_keypaths = [kp for kp in b_data.keypaths() if re.fullmatch(filter, kp)]
filtered_data = b_data.subset(filtered_keypaths)

assert filtered_data == {"items": [{"name": "a"}, {"name": "b"}]} 

Just like what map() works in the functional programming.

@momocow momocow added the enhancement New feature or request label Mar 26, 2020
@fabiocaccamo
Copy link
Owner

fabiocaccamo commented Mar 26, 2020

This is really an interesting feature.

I think that subset could be improved to accept also a regex to do exactly what you need with just 1 line of code.

@fabiocaccamo
Copy link
Owner

fabiocaccamo commented Sep 22, 2020

@momocow with 0.21.0 version you can retrieve keypaths including indexes:

data = {"items": ["a", {"c": 1}]}
kps = benedict(data).keypaths(indexes=True)
assert kps == [
    "items",
    "items[0]",
    "items[1]",
    "items[1].c"
]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants