欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

编写函数处理user_list,新方法

程序员文章站 2022-06-14 16:01:21
写函数,完成以下功能: # 例如有: user_list=[ {"name": "alex","hobby":"抽烟"}, {"name" :"alex","hobby":"喝酒"}, {"name" :"alex","hobby":"烫头"}, {"name":"wusir","hobby&qu...
写函数,完成以下功能: 
# 例如有:
user_list=[
    {"name": "alex","hobby":"抽烟"},
    {"name" :"alex","hobby":"喝酒"},
    {"name" :"alex","hobby":"烫头"},
    {"name":"wusir","hobby":"喊麦"},
    {"name":"wusir","hobby":"街舞"},
          ]
# 编写函数处理user_list 并返回如下结果:
# [{"name":"alex","hobby_list": ["抽烟","喝酒","烫头"]},
# {"name":"wuhir","hobby_list": ["喊麦","街舞"]},]

old_dict = dict()
aim_list = []

for a in user_list:
    k, v = a.values()
    old_dict.setdefault(k, []).append(v)

# old_dict = {'alex': ['抽烟', '喝酒', '烫头'], 'wusir': ['喊麦', '街舞']}

for k, v in old_dict.items():
    new_dict = dict()
    new_dict['name'] = k
    new_dict['hobby'] = v
    aim_list.append(new_dict)

print(aim_list)