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

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 this issue Jul 29, 2023 · 1 comment

Comments

@jj-github-jj
Copy link

jj-github-jj commented Jul 29, 2023

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(dict_in, prefix = "N_",strip_char=''):
""" 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(dict_in) # 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(strip_char) 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,strip_char='_'):
""" 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
Copy link

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

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

No branches or pull requests

2 participants