<pre><code>field_to_be_check ="state"
merger = ["city", "ads"]
merge_name = ["cities", "my_ads"]
data = [
{'haps': 'hap0', 'state': 'tamil nadu', 'ads': 'ad1', 'city': 'tirunelveli'},
{'haps': 'hap0', 'state': 'tamil nadu', 'ads': 'ad4', 'city': 'nagerkoil'},
{'haps': 'hap0', 'state': 'tamil nadu', 'ads': 'ad1', 'city': 'tuticorin'},
{'haps': 'hap0', 'state': 'tamil nadu', 'ads': 'ad1', 'city': 'madurai'},
{'haps': 'hap0', 'state': 'tamil nadu', 'ads': 'ad1', 'city': 'chennai'},
{'haps': 'hap1', 'state': 'kerala', 'ads': 'ad2', 'city': 'palakad'},
{'haps': 'hap1', 'state': 'kerala', 'ads': 'ad2', 'city': 'guruvayor'},
{'haps': 'hap1', 'state': 'kerala', 'ads': 'ad2', 'city': 'kolikodu'},
{'haps': 'hap1', 'state': 'kerala', 'ads': 'ad2', 'city': 'kottayam'},
{'haps': 'hap1', 'state': 'kerala', 'ads': 'ad2', 'city': 'idukki'},
{'haps': 'hap2', 'state': 'mumbai', 'ads': 'ad3', 'city': 'Akola'},
{'haps': 'hap2', 'state': 'mumbai', 'ads': 'ad3', 'city': 'Washim'},
{'haps': 'hap2', 'state': 'mumbai', 'ads': 'ad3', 'city': 'Jalna'},
{'haps': 'hap2', 'state': 'mumbai', 'ads': 'ad3', 'city': 'Nanded'},
{'haps': 'hap2', 'state': 'mumbai', 'ads': 'ad3', 'city': 'Latur'}
]
# merger and merge_name must be one to one.
the_dict = {m:mn for m, mn in zip(merger, merge_name)}
# {"city":"cities", "ads":"my_ads"} merge_name
newdata = data.copy()
# create new_ret as result
new_ret = [{field_to_be_check:i, **{i:[] for i in merge_name}} for i in set([i[field_to_be_check] for i in data])]
# print(new_ret, "this is new_ret")
for val in new_ret:
for k in newdata:
if val[field_to_be_check] != k[field_to_be_check]:
continue
tmp = {i:k[i] for i in merger}
for single in tmp:
if {single:tmp[single]} not in val[the_dict[single]]:
val[the_dict[single]].append({single:tmp[single]})
print(new_ret)
</code></pre>