2017-11-26 19 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

ああ、うわー、あなたはちょうどそのコードをもっときれいにしました、ありがとう!私は変数として "プロファイル[キー]"を見ていると思いますので、プロファイル[キー]は '値'が配置されている 'ボックス'です。しかし、あなたは "プロファイル[キーが変数 "値"を保持していないのですが、辞書構文の一部にすぎませんか? – User31899

+0

はい正しいです。 –

0

これは何も変換していないので、少し混乱するかもしれないと思います。what a dictionary is

具体的には、辞書は、keyおよびvalueのペアのコレクションです。

それがリストだった場合、すなわち、それは次のようになります。ループ内で何が起こっている

[("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