1defsolve(*args):2 res =dict()3for d in args:4for k, v in d.items():5 res[k]= res.get(k,[])+[v]6for k, v in res.items():7ifisinstance(v[0],int):8 res[k]= v[-1]9elifisinstance(v[0],list):10 res[k]=[lst[j:j+1][0]for j inrange(max([len(i)for i in v]))for lst in v if lst[j:j+1]!=[]]11elifisinstance(v[0],dict):12 res[k]= solve(*v)13else:14raise TypeError
15return res
1617A ={'apple':1,18'banana':{'cherry':2,'dekopon':[1,9],'egg':4}}19B ={'banana':{'cherry':1,'dekopon':[3,6,2],'feijoa':5,}}20C ={'apple':5,21'banana':{'dekopon':[3]},22'grape':9}23D ={'banana':{'dekopon':[4,7],'feijoa':6}}2425ans = solve(A, B, C, D)26print(ans)
1from itertools import zip_longest, chain
23defsolve(*args):4defmy_update(k, v, base):5if k notin base orisinstance(v,int):6 base[k]= v
7elifisinstance(v,list):8 base[k]+=[None]+ v
9elifisinstance(v,dict):10for kk, vv in v.items():11 my_update(kk, vv, base[k])12else:13raise TypeError # str型 や set型などの処理は未実装1415defupdate_list(x):16ifisinstance(x,list):17 sp =[-1]+[i for i, e inenumerate(x)if e isNone]+[len(x)]18 res =[x[l+1:r]for l, r inzip(sp, sp[1:])]19 x[:]=list(filter(lambda e: e isnotNone, chain.from_iterable(zip_longest(*res))))20elifhasattr(x,'__getitem__'):21for k, v in x.items():22 update_list(v)2324 res =dict()25for d in args:26for k, v in d.items():27 my_update(k, v, res)28 update_list(res)29return res
303132A ={'apple':1,33'banana':{'cherry':2,'dekopon':[1,9],'egg':4}}34B ={'banana':{'cherry':1,'dekopon':[3,6,2],'feijoa':5,'foo':{'bar':{'baz':[1,2]}}}}35C ={'apple':5,36'banana':{'dekopon':[3],'foo':{'bar':{'baz':[3,4]}}},37'grape':9}38D ={'banana':{'dekopon':[4,7],'feijoa':6}}3940ans = solve(A, B, C, D)41print(ans)