user_list = [{"name":"alex","hobby":"抽烟"},
{"name":"alex","hobby":"喝酒"},
{"name":"alex","hobby":"烫头"},
{"name":"wusir","hobby":"喊麦"},
{"name":"wusir","hobby":"街舞"},
]
编写函数处理 user_list并返回如下结果:
[{"name":"alex","hobby_list":["抽烟","喝酒","烫头"]},{"name":"wusir","hobby_list":["喊麦","街舞"]}]
user_list = [{"name":"alex","hobby":"抽烟"},
{"name":"alex","hobby":"喝酒"},
{"name":"alex","hobby":"烫头"},
{"name":"wusir","hobby":"喊麦"},
{"name":"wusir","hobby":"街舞"},
]
list = []
for user in user_list:
# print(user)
for new_user in list:
if user["name"] == new_user["name"]:
new_user.setdefault("hobby_list",[]).append(user["hobby"])
break
else:
dic = {}
dic["name"] = user["name"]
dic["hobby_list"] = [user["hobby"]]
list.append(dic)
print(list)