Python 任意数量的关键字实参

将函数编写成能够接受任意数量的键-值对——调用语句提供类多少就接受多少,直接看下面例子:

 1 >>> def build_profile(first,last,**user_info):
 2 ...     profile = {}
 3 ...     profile['first_name'] = first
 4 ...     profile['last_name'] = last
 5 ...     for key,value in user_info.items():
 6 ...             profile[key] = value
 7 ...     return profile
 8 ... 
 9 >>> user_profile = build_profile('albert','einstein',location='princeton',field='physics')
10 >>> print(user_profile)
11 {'last_name': 'einstein', 'location': 'princeton', 'first_name': 'albert', 'field': 'physics'}

 

posted @ 2017-05-17 13:38  Bio-Liu  阅读(1025)  评论(0编辑  收藏  举报