Python 用户配置文件字典循环

Python 用户配置文件字典循环,python,dictionary,key,Python,Dictionary,Key,这里有一个基本的问题给你们这些了不起的家伙。我对编码是一个相当陌生的人,当我看到这段代码时,我就是想不出来。问题是:为什么profile[key]=value在这个特定循环中?似乎这段代码正在将字典键变成一个值,这在我的脑海中是没有意义的,任何解释都会很棒!守则: def build_profile(first, last, **user_info): """Build a dictionary containing everything we know about a user"""

这里有一个基本的问题给你们这些了不起的家伙。我对编码是一个相当陌生的人,当我看到这段代码时,我就是想不出来。问题是:为什么
profile[key]=value
在这个特定循环中?似乎这段代码正在将字典
变成一个
,这在我的脑海中是没有意义的,任何解释都会很棒!守则:

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)

另外,这是在“Python速成课程”的第153页上——它给出了一个解释,但我就是不明白,对不起。

你误解了
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]

访问存储在字典中的值。您误解了
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]

访问存储在dictionary中的值。它没有转换任何内容,我想您可能会有点困惑

具体来说,字典是
对的集合

i、 e.如果它是一个列表,它将如下所示:

[("first_name", "albert"),
 ("last_name", "einstein"),
 ("location", "princeton"),
 ("field", "physics")]
循环内部发生的情况是(在伪代码中):


你可能会发现理解很有帮助。

这并不能转化任何东西,我想你可能会有点困惑

具体来说,字典是
对的集合

i、 e.如果它是一个列表,它将如下所示:

[("first_name", "albert"),
 ("last_name", "einstein"),
 ("location", "princeton"),
 ("field", "physics")]
循环内部发生的情况是(在伪代码中):


您可能会发现理解很有帮助。

很有趣,所以**Kwarg实际上是作为字典类型来构造的?我以为它们被格式化为元组类型,或者我想的是*args?很有趣,那么**kwargs实际上是作为字典类型构造的?我以为它们被格式化为tuple_类型,或者我想的是*args?哦,哇,你刚刚让代码更简洁了,谢谢!我想我将“profile[key]”视为一个变量,因此profile[key]是“值”所在的“框”。但是你似乎在说“profile[key]不包含变量”值,而只是字典语法的一部分,对吗?哦,哇,你刚刚让代码更简洁了,谢谢!我想我把“profile[key]”看作是一个变量,因此,profile[key]是“值”所在的“框”。但您似乎在说“profile[key]不包含变量“value”,而只是字典语法的一部分,对吗?