1. 程式人生 > >字典合併去重

字典合併去重

這個題目在網上找了好多種不同的答案沒找到自己想要的

案例:

把lst3的程式碼轉成lst4的格式
	lst3 = [
	{"name":"張三","habby":"吸菸"},
	{"name":"張三","habby":"燙頭"},
    {"name":"張三","habby":"早戀"},
    {"name":"張三","habby":"喝酒"},
    {"name":"李四","habby":"寫程式碼"},
    {"name":"李四","habby":"看部落格"},]
lst4 = [{"name":"張三","habby":["吸菸","燙頭","早戀","喝酒"]},
        {"name":"李四","habby":["寫程式碼","看部落格"]}]

  要把lst3字典轉成lst4格式的題

 

l = []  # 用來去重鍵
lst4 = []  # 建立一個新的空列表
for dic in lst3:
    name = dic['name']  # 迴圈拿到name鍵
    try:
        index = l.index(name)#name在l中的下標
        lst4[index]['habby'].append(dic['habby'])
    except: #如果沒有Index
        lst4.append({'name': name, 'habby': [dic["habby"]]})
        l.append(name)
print(lst4)