用户配置文件字典循环

2024-06-07 23:15:02 发布

您现在位置:Python中文网/ 问答频道 /正文

这里有一个基本的问题给你们这些了不起的家伙。我是一个相当新的人来编码,当我看到这个代码,我只是不明白它。问题是:profile[key] = value为什么在那个特定的循环中?好像这个代码把字典{{CD2}}变成了^ {CD3}},这在我的脑子里是没有意义的,任何解释都是伟大的!代码:

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)

另外,这是在第153页的“Python速成课程”-它给出了一个解释,但我只是不明白,对不起。你知道吗


Tags: thekey代码namebuildinfo编码dictionary
2条回答

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

它没有转换任何东西,我想您可能对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很有帮助。你知道吗

相关问题 更多 >

    热门问题