我們如何合并具有相同“id”和條件的字典來合并“test_type”值?
輸入:
[{id:'abc', type:'test', test_type:['404']},
{id:'def', type:'test', test_type:['404','server_error']},
{id:'abc', type:'test', test_type:['server_error']},
{id:'abc', type:'test', test_type:['server_error', '404']}]
預期輸出:
[{id:'abc', type:'test', test_type:['404','server_error']},
{id:'def', type:'test', test_type:['404','server_error']}]
uj5u.com熱心網友回復:
original_list = [{id:'abc', type:'test', 'test_type':['404']},
{id:'def', type:'test', 'test_type':['404','server_error']},
{id:'abc', type:'test', 'test_type':['server_error']},
{id:'abc', type:'test', 'test_type':['server_error', '404']}]
new_list = []
new_dict = {}
for old_dict in original_list:
if old_dict[id] not in new_dict:
new_dict[old_dict[id]] = old_dict
else:
present_values = new_values = []
if 'test_type' in new_dict:
present_values = new_dict[old_dict[id]]['test_type']
if 'test_type' in old_dict:
new_values = old_dict['test_type']
temp_list = list(set(present_values new_values))
new_dict[old_dict[id]]['test_type'] = temp_list
final_list = list(new_dict.values())
print(final_list)
uj5u.com熱心網友回復:
這是使用itertools.groupby(用于創建基于鍵的字典組)和collections.defaultdict(用于合并字典)的干凈方法。
請在行內注釋中找到解釋。隨時在評論中提出任何問題。
from itertools import groupby
from collections import defaultdict
f = lambda x: x['id'] #condition for sorting & grouping
groups = groupby(sorted(l, key=f), f) #creating grouper object
output = []
for _ , g in groups:
d = defaultdict(list)
for i in g:
d['id'], d['type'] = i['id'], i['type'] #set id and type as same
d['test_type'].extend(i['test_type']) #extend list of test_type
d['test_type'] = list(set(d['test_type'])) #reset test_type as unique values
output.append(dict(d))
[{'id': 'abc', 'test_type': ['404', 'server_error'], 'type': 'test'},
{'id': 'def', 'test_type': ['404', 'server_error'], 'type': 'test'}]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/400137.html
上一篇:從目錄創建嵌套字典
