小编ude*_*tha的帖子

将嵌套字典中的所有键从camelCase转换为snake_case

我有一本类似这样的字典:

{
     'firstName': 'abc',
     'lastName': 'xyz',
     'favoriteMovies': ['Star Wars', 'The lone ranger'],
     'favoriteCountries': [
          {'country': 'China', 'capitalCity': 'Beiging'},
          {'country': 'India', 'capitalCity': 'New Delhi'}
     ]
}
Run Code Online (Sandbox Code Playgroud)

我想将其转换为snake_case,如下所示

{
    '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'}
     ]
}  
Run Code Online (Sandbox Code Playgroud)

字典可以是任何长度深度。

我目前的解决方案是

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 …
Run Code Online (Sandbox Code Playgroud)

python algorithm

6
推荐指数
3
解决办法
1万
查看次数

标签 统计

algorithm ×1

python ×1