import json
tmp_site_type = [{'type': '比價', 'word': '折扣'}, {'type': '比價', 'word': '禮品'}, {'type': '比價', 'word': '特價'}]
tmp_dict = dict()
for l in tmp_site_type:
if l.get("type") in tmp_dict:
tmp_dict[l.get("type")]["words"].append(l.get("word"))
else:
tmp_d = dict()
words = list()
words.append(l.get("word"))
tmp_d["words"] = words
tmp_dict[l.get("type")] = tmp_d
tmp_list = list()
for key, value in tmp_dict.items():
tmp_d = dict()
tmp_d["type"] = key
tmp_d["words"] = value.get("words")
tmp_d["number"] = len(value.get("words"))
tmp_list.append(tmp_d)
import json
print(json.dumps(tmp_list, indent=4, ensure_ascii=False))
輸出
[
{
"type": "比價",
"words": [
"折扣",
"特價"
],
"number": 2
},
{
"type": "新聞",
"words": [
"新聞"
],
"number": 1
}
]