Enhancement Request
Closed this issue · 3 comments
aymanhs commented
Love this project.
Just small requests. I'll try to put in a Pull Request
- Add pathseparator. So if '. ' can possibly be in the keys, then someone can use "/" as separator
- Add support for regex or wildcard match on keys so that one does not need full key name.
perfecto25 commented
Thanks for feedback,
the separator for dot keys is already there,
{
"dirty.harry": {
"year": 1977,
"genre": "romance"
},
}
searching for dictor(data, 'dirty.harry') will return a None since Dictor sees the dot-separated entry as 2 separate keys.
To search for a key with a dot in it, simply use an escape character ".",
dictor(data, 'dirty\.harry')
{u'genre': u'romance', u'year': 1977}
as for regex, this is a good idea, but not sure how to handle if regex finds multiple results, ie,
data = {
"names":
{
"marius": "employee",
"mark": "employee",
"marcella": "employee",
"bob": "employee"
}
}
dictor(data, 'names.mar*')
// will match 3 out of 4 keys
Maybe an option is to match the 1st regex result it finds?
aymanhs commented
Seems I have oversimplified the implementation quiet a bit :-)
def dictor(data, path=None, default=None, checknone=False, ignorecase=False, pathsep="."):
if path is None or path == '':
return data
try:
for key in path.split(pathsep):
if isinstance(data, (list, tuple)):
val = data[int(key)]
else:
if ignorecase:
for datakey in data.keys():
if datakey.lower() == key.lower():
key = datakey
break
val = data[key]
data = val
except (KeyError, ValueError, IndexError, TypeError):
val = default
if checknone:
if not val or val == default:
raise ValueError('value not found for search path: "%s"' % path)
return val
For using regex, I'm thinking the regex should return the first match, since ideally, there should only be one.
perfecto25 commented
PR merged