当前位置: 首页 > 工具软件 > dict_build > 使用案例 >

python dict 相同value key值_将具有相同keyvalue对的多个dict合并到一个dict python

康照
2023-12-01

这是一个完美的场景来展示itertools.groupby的威力

请注意,我假设hap、state和ads将出现在所有字典中,并且在重复中也会相似from itertools import groupby

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'}

]

#Function to make the merger lists

def process_group(group, merger_item):

item_set = set()

item_list = []

for item in group:

item_set.add(item[merger_item])

for item in item_set:

item_list.append({merger_item: item})

return item_list

#Group on haps, state and ads

grp = groupby(data,key=lambda x:(x[field_to_be_check]))

result = []

#Iterate through the group and build your result list

for model, group in grp:

cities_dict = {}

cities_dict[field_to_be_check] = model

group_list = list(group)

#Make the list for merger fields

for idx, name in enumerate(merger):

cities_dict[merge_name[idx]] = process_group(group_list, name)

result.append(cities_dict)

print(result)

输出看起来像

^{pr2}$

 类似资料: