生成字典小技巧

# 将list3 这种数据类型转化成list4类型
list3 = [
{"name": "a", "hobby": "抽烟"},
{"name": "a", "hobby": "喝酒"},
{"name": "a", "hobby": "烫头"},
{"name": "a", "hobby": "Massage"},
{"name": "b", "hobby": "喊麦"},
{"name": "b", "hobby": "街舞"},
{"name": "b", "hobby": "出差"},
]
list4 = [
{"name": "a", "hobby_list": ["抽烟", "喝酒", "烫头", "Massage"]},
{"name": "b", "hobby_list": ["喊麦", "街舞","出差"]},
]
1.
# dic={}
# for i in list3:
# if i["name"] in dic:
# dic[i["name"]]["hobby_list"].append(i["hobby"])
# else:
# dic[i['name']] = {'name': i['name'], 'hobby_list': [i['hobby'], ]}
# print(list(dic.values()))
1.1
# dic = {}
# for i in list3:
# if i['name'] not in dic:
# dic[i['name']] = {'name': i['name'],'hobby_list':[i['hobby'],]}
# else:
# dic[i['name']]['hobby_list'].append(i['hobby'])
# print(list(dic.values()))
2.
# l1=[]
# for i in list3:
# for j in l1:
# if i['name'] == j['name']:
# j['hobby_list'].append(i['hobby'])
# break
# else:
# l1.append({'name': i['name'], 'hobby_list':[i['hobby'],]})
# print(l1)

3.
# li=[]
# lis=[]
# dic={"name":"","hobby_list":[]}
# for i in range(len(list3)):
# li.append(list3[i]["name"])
# li=list(set(li))
# print(li)
# for i in li:
# dic={}
# dic["name"]=i
# dic["hobby_list"]=[]
# for k in range(len(list3)):
# if i==list3[k]["name"]:
# dic["hobby_list"].append(list3[k]["hobby"])
# lis.append(dic)
# print(lis)
posted @ 2020-06-14 15:35  diracy  阅读(95)  评论(0编辑  收藏  举报