LarsHill / metadict

MetaDict is a powerful dict subclass enabling (nested) attribute-style item access/assignment and IDE autocompletion support.
Apache License 2.0
31 stars 1 forks source link

Feature Request (Not a bug) . support option to convert keys to valid python names for dot notation access to keys with spaces etc #10

Open jj-github-jj opened 1 year ago

jj-github-jj commented 1 year ago

I find metadict very useful but find a lot of times dicts have keys that are not valid python names so not useable with auto completion using dot notation.

I used the following workaround and wondering if a proper implementation of the following idea could be incorporated as an option to enhance MetaDict class so it can support optional conversion to valid names for keys so all dict keys are accessible using dot notation.

def convert_keys_to_valid_names(dictin, prefix = "N",stripchar=''): """ convert keys to valid strings for use in MetaDict which support dot notation access for dictionaries - tab completion dict keys can be integers but integers are not supported in dot access so convert to strings with prefix. """ dictionary = dict(dictin) # in case iterable is passed, first convert to dictionary return {(prefix+str(key) if isinstance(key, int) else prefix + re.sub(r'\W+', '', key).strip(stripchar) if key[0].isnumeric() \ else re.sub(r'\W+', '', key).strip(strip_char)): value for key, value in dictionary.items()}

def myMetaDict(dict_in,nested_assignment=False,stripchar=''): """ dot notation dict by using MetaDict with python valid transformed keys""" return ( MetaDict(convert_keys_to_valid_names(dict_in,strip_char=strip_char),nested_assignment=nested_assignment))

Kodiologist commented 1 month ago

Likewise it would be nice to have an option to rename keys like items and keys.