1. 程式人生 > >day14 記錄一道Python列表格式轉換的題目

day14 記錄一道Python列表格式轉換的題目

lis3 = [
    {"name": "alex", "hobby": "抽菸"},
    {"name": "alex", "hobby": "喝酒"},
    {"name": "alex", "hobby": "燙頭"},
    {"name": "alex", "hobby": "message"},
    {"name": "wusir", "hobby": "喊麥"},
    {"name": "wusir", "hobby": "街舞"},
    {"name": "太白", "hobby": "看片"},

]

lis4 = [] 將lis3轉換為[{'name': 'alex', 'hobby_list': ['抽菸', '喝酒', '燙頭', 'message']}, {'name': 'wusir', 'hobby_list': ['喊麥', '街舞']}]

for el3 in lis3:
    for el4 in lis4:
        if el3["name"] == el4["name"]:
            el4["hobby_list"].append(el3["hobby"])
            # el4.setdefault("hobby_list",[]).append(el3["hobby"])
            break
    else:
        lis4.append({"name": el3["name"], "hobby_list": [el3["hobby"]]})

print(lis4)