perfecto25/dictor

Enhancement Request

Closed this issue · 3 comments

Love this project.

Just small requests. I'll try to put in a Pull Request

  1. Add pathseparator. So if '. ' can possibly be in the keys, then someone can use "/" as separator
  2. Add support for regex or wildcard match on keys so that one does not need full key name.

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?

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.

PR merged