I have a dictionary something like this:
{
'firstName': 'abc',
'lastName': 'xyz',
'favoriteMovies': ['Star Wars', 'The lone ranger'],
'favoriteCountries': [
{'country': 'China', 'capitalCity': 'Beiging'},
{'country': 'India', 'capitalCity': 'New Delhi'}
]
}
I want to convert it to snake_case like the following
{
'first_name': 'abc',
'last_name': 'xyz',
'favorite_movies': ['Star Wars', 'The lone ranger'],
'favorite_countries': [
{'country': 'China', 'capital_city': 'Beiging'},
{'country': 'India', 'capital_city': 'New Delhi'}
]
}
The dictionary may be of any length depth.
My current solution is
import re
def convert_snake_case_to_camel_case(data):
required_dict = {}
for key, value in data.items():
if type(value) == str:
new_key = re.sub("([a-z0-9])([A-Z])", r"\1_\2", key).lower()
required_dict[new_key] = value
elif type(value) == list and all(list(map(lambda _: isinstance(_, str), value))):
new_key = re.sub("([a-z0-9])([A-Z])", r"\1_\2", key).lower()
required_dict[new_key] = value
elif type(value) == list and all(list(map(lambda _: isinstance(_, dict), value))):
new_key = re.sub("([a-z0-9])([A-Z])", r"\1_\2", key).lower()
required_dict[new_key] = list(filter(convert_snake_case_to_camel_case, value))
return required_dict
But I m not getting the expected result for the nested data.