본문 바로가기
Programing Language/Python

[Python] Snake Case To Camel Case ( str, dict, list )

by pcm9881 2023. 5. 30.

다른 API 호출을 위해 Python에서는 기본적으로 변수명Snake Case를 사용하기 때문에 API 요청보낼 때 Key값을 Camel Case로 변환하는 함수를 만들었습니다.

 

1.  Snake Case To Camel Case

스네이크 케이스( Snake Case ) 문자열을 카멜 케이스( Camel Case ) 문자열로 변환하는 함수입니다.

def convert_snake_case_to_camel_case(snake_case_str: str):
    if "_" not in snake_case_str:
        return snake_case_str

    temp = snake_case_str.split("_")

    return temp[0] + "".join(ele.title() for ele in temp[1:])

 

 

2.  Snake Case To Camel Case ( Dictionary )

딕셔너리( Dictionary )에 Key값만 꺼내서 새로운 딕셔너리( Dictionary )에 담아 리턴(return)하는 함수입니다.

def dict_key_convert_snake_case_to_camel_case(old_dict: dict):
    new_dict = {}
    old_dict_keys = old_dict.keys()
    for old_key in old_dict_keys:
        new_dict[f"{convert_snake_case_to_camel_case(old_key)}"] = old_dict[old_key]

    return new_dict

 

 

3.  Snake Case To Camel Case ( List )

딕셔너리 리스트( Dictionary List )를 변환해서 리턴하는 함수입니다.

def list_key_convert_snake_case_to_camel_case(old_list: dict):
    new_list = []
    for old_dict in old_list:
        new_list.append(dict_key_convert_snake_case_to_camel_case(old_dict))

    return new_list

 

 

4.  전체

def convert_snake_case_to_camel_case(snake_case_str: str):
    if "_" not in snake_case_str:
        return snake_case_str

    temp = snake_case_str.split("_")

    return temp[0] + "".join(ele.title() for ele in temp[1:])


def dict_key_convert_snake_case_to_camel_case(old_dict: dict):
    new_dict = {}
    old_dict_keys = old_dict.keys()
    for old_key in old_dict_keys:
        new_dict[f"{convert_snake_case_to_camel_case(old_key)}"] = old_dict[old_key]

    return new_dict


def list_key_convert_snake_case_to_camel_case(old_list: dict):
    new_list = []
    for old_dict in old_list:
        new_list.append(dict_key_convert_snake_case_to_camel_case(old_dict))

    return new_list

 

 

참조

[긱스포긱스]: https://www.geeksforgeeks.org/python-convert-snake-case-string-to-camel-case/

 

Python - Convert Snake Case String to Camel Case - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

 

728x90

댓글