首页 > 技术文章 > Python结合使用位置实参和任意数量实参

hhjfighting 2017-11-13 10:50 原文

def build_profile(first,last,**user_info):    #**号创建空字典
"""creat a dictionary,including all of users which we know"""
  profile = {}               #程序的关键部分就是字典的建立,首先有一个空字典为接下来的键值对建立做准备
  profile['first_name'] = first           #创建字典内的键值对,通过这个方式将实参输入字典
  profile['last_name'] = last         #同上
  for key,value in user_info.items():        #以循环的方式应对任意数量形参的输入,通过方法items()将键值分别赋给key,value
    profile[key] = value        #变量赋值,将上一步分别获得的key和value进行关联
  return profile              #实际需要的是 profile 这个字典
user_profile = build_profile('Huang','Jerry',age=21,agree='college',  #注意这里的字典键值对中间是等号
              lover='Eurus Dai')
print(user_profile)            #以字典形式打印信息

 

推荐阅读