TIL/Python
dictionary를 이용한 함수
hyo-min
2024. 2. 20. 19:13
이 함수가 이해가 안되서 혼자 한참이나 들여다보고 GPT한테도 물어보고 결국 이해가 됐기에 기록해둔다.
def set_profile(**kwargs):
profile = {}
profile["name"] = kwargs.get("name", "-")
profile["gender"] = kwargs.get("gender", "-")
profile["birthday"] = kwargs.get("birthday", "-")
profile["age"] = kwargs.get("age", "-")
profile["phone"] = kwargs.get("phone", "-")
profile["email"] = kwargs.get("email", "-")
return profile
user_profile = {
"name": "lee",
"gender": "man",
"age": 32,
"birthday": "01/01",
"email": "python@sparta.com",
}
print(set_profile(**user_profile))
""" 아래 코드와 동일
profile = set_profile(
name="lee",
gender="man",
age=32,
birthday="01/01",
email="python@sparta.com",
)
set_profile( **kwargs ): # ** 연산자는 dictionary를 "키워드 인자"로 전달하는 데 사용. 따라서 kwargs 는 dictionary
profile { } # 'profile' 이라는 빈 dict 생성
profile ['name'] # 'profile' dict에 'name'인 key 생성
= kwargs.get('name', ' - ') # 'name'에 value가 있으면 그 값을 반환하고 없다면 '-' 반환
return profile # profile 값 반환
print(set_profile(**user_profile)) # 'user_profile' dict 전부 인자로 넣기