重点

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

result = []  #里面放{'name':'alex','hobby_list':['抽烟','喝酒','烫头']}

def main(user_list):

    for user in user_list:

        for new_user in result:
            if user['name'] == new_user['name']:  #如果有相同的名字就在hobbylist后面添加新的
                new_user['hobby_list'].append(user['hobby'])
                break
        else:  #如果没有就创建一个新字典
            dic = {}
            dic['name'] =  user['name']
            dic['hobby_list'] = [user['hobby']]
            result.append(dic)
    print(result)


main(user_list)

 

posted @ 2019-07-06 17:13  s686编程传  阅读(170)  评论(0编辑  收藏  举报