实参中有三个键值对,为啥跑出来字典中只出现了一个

代码:
def build_profile(first, last, **user_info):
创建一个字典,其中包含用户的一切
profile = {}
profile['first_name'] = first
profile['last_name'] = last
for key, value in user_info.items():
profile['key'] = value #出错行
return profile

user_profile = build_profile('Liu', 'Cy',
age = '22',
sex = '女',
location = 'China'
)
print(user_profile)

结果:{'first_name': 'Liu', 'last_name': 'Cy', 'key': 'China'}

已知profile['key'] = value中key的引号应该去掉,但是如果就按照错误的写法,实参中有三个键值对,为什么跑出来只出现了'key': 'China'。并没有'key':'22','key':'女'呢。

这个时候,带引号的'key'就是一个键了,由于字典中的键不能重复,如果有多个值对同一键赋值,则取最后一个

改了一下,key不能用引号包起来

def build_profile(first, last, **user_info):
    #创建一个字典,其中包含用户的一切
    profile = {}
    profile['first_name'] = first
    profile['last_name'] = last
    for key, value in user_info.items():
        profile[key] = value #出错行
    return profile

user_profile = build_profile('Liu', 'Cy',
age = '22',
sex = '女',
location = 'China'
)
print(user_profile)

因为你把key用引号括起来了,这样只有一个名叫‘key’的键,而不是循环里的变量key
profile['key'] = value