2017-11-26 11 views
1

여기에 여러분을위한 기본적인 질문이 있습니다. 저는 코드 작성에 상당히 새로운 사람입니다.이 코드를 보았을 때, 나는 그것을 이해할 수 없었습니다. 다음은 질문입니다. 왜 특정 루프에 profile[key] = value입니까? 이 코드가 사전 keyvalue으로 만들어 내 머리에서 이해가되지 않는 것 같습니다. 어떤 설명이 좋을 것입니다! 코드 :user_profile 사전 루프

def build_profile(first, last, **user_info): 
    """Build a dictionary containing everything we know about a user""" 

    profile = {} 
    profile["first_name"] = first 
    profile["last_name"] = last 

    for key, value in user_info.items(): 
     profile[key] = value # Why is this converting the key of the dictionary into a value? 
    return profile 

user_profile = build_profile("albert", "einstein", 
          location="princeton", 
          field="physics") 

print(user_profile) 

P.S. 이것은 "Python Crash Course"의 153 페이지에 있습니다. 설명을 주었지만 이해가되지 않습니다. 죄송합니다.

답변

0

당신은 무엇을 오해하고 있습니까 profile[key] = value 않습니다. 사전은 키, 값 쌍으로 구성됩니다.

# when you do this: 
for key, value in user_info.items(): #should be user_info.iteritems() because dict.items() is deprecated. 
    profile[key] = value 

# you are basically copying the user_info dict, which can be done much easier this way: 
profile = user_info.copy() 

그래서 profile[key] = value 수단은 영어로, 당신은 사전 profile의 키를 생성하고 있는지 값에 할당. 사전에 저장된 값에 dictionary[key]으로 액세스 할 수 있습니다.

+0

오, 와우, 방금 코드를 훨씬 더 깨끗하게 만들었습니다. 감사합니다! 나는 "profile [key]"를 변수로 보았을 것입니다. profile [key]는 'value'가 위치하는 'box'입니다. 그러나 여러분이 "profile [ key] 변수 "value"를 보유하고 있지 않지만 사전 구문의 일부일뿐입니다. 맞습니까? – User31899

+0

맞습니다. –

0

아무 것도 변환하지 않으므로 조금 혼동 스러울 수도 있습니다. what a dictionary is.

즉, 사전 keyvalue의 모음이다. 이 목록 인 경우

즉, 그 결과는 다음과 같습니다 루프 내부에서 무슨 일이 일어나고 무엇

[("first_name", "albert"), 
("last_name", "einstein"), 
("location", "princeton"), 
("field", "physics")] 

이 (의사 코드)입니다 :

foreach function_argument # (e.g. location="princeton") 
    get the parameter name # (e.g. "location") 
    get the argument value # (e.g. "princeton") 

    create a new key-value pair in the profile: # (profile[key] = value) 
     the key = the parameter name 
     the value = the argument value 

당신은 the difference between a parameter and an argument가 도움이 이해 찾을 수 있습니다.

+0

흥미 롭습니다. 따라서 ** kwargs는 실제로 dictionary_type으로 구조화되어 있습니까? 나는 tuple_type 형식으로 생각했습니다. 또는 아마 내가 args 생각하고있어? – User31899