根据特定键合并2个字典列表

时间:2019-03-28 12:05:29

标签: python list dictionary

我需要根据特定键合并两个字典列表,否则需要追加

我使用以下代码生成了字典列表,并且按我的主要问题可以预期的工作是当我尝试 合并两个不同的列表,如果找到相同的键,那么我需要根据字典键附加该值。

feed_mapping = {'BC': 11, 'HA':12, 'AB':16,'GR':18}
L = ["AB-24519152","BC-24519152"]

years_dict = dict()
l1 = []
for line in L:
    feed_id = feed_mapping[line.split('-')[0]]
    if feed_id in years_dict:
        # append the new number to the existing array at this slot
        years_dict[feed_id].append(line)
    else:
        # create a new array in this slot
        years_dict[feed_id] = [line]


for element,values in years_dict.items():
    l1.append({"id":values,"feed":element})


print(l1)


l1=  [{'id': ['AB-23473427','AB-99999'], 'feed': 16}, {'id': ['HA-4848231'], 'feed': 12}]
l2 = [{'id': ['AB-23473427'], 'feed': 14}, {'id': ['HA-4848231'], 'feed': 12}]

预期输出:

[{'id': ['AB-23473427','AB-99999'], 'feed': 16}, {'id': ['HA-4848231','HA-4848231'], 'feed': 12},{'id': ['AB-23473427'], 'feed': 14}]

2 个答案:

答案 0 :(得分:2)

您应该利用更适合此任务的数据结构,它实际上是您自己的years_dict

from collections import defaultdict
l1=  [{'id': ['AB-23473427','AB-99999'], 'feed': 16}, {'id': ['HA-4848231'], 'feed': 12}]
l2 = [{'id': ['AB-23473427'], 'feed': 14}, {'id': ['HA-4848231'], 'feed': 12}]

temp = defaultdict(list) 

for i in l1:
    temp[i['feed']].extend(i['id'])

for i in l2:
    temp[i['feed']].extend(i['id'])

#Notice that temp is essentially same as years_dict, but with information of both lists
result = [{"id":v,"feed":k} for k,v in temp.items()]
#Output:
[{'id': ['AB-23473427', 'AB-99999'], 'feed': 16},
 {'id': ['HA-4848231', 'HA-4848231'], 'feed': 12},
 {'id': ['AB-23473427'], 'feed': 14}]

因此,尽管此代码有效,但我的建议是保留所有列表的years_dict,并只在最后将其转换为最终输出。

答案 1 :(得分:1)

l1=  [{'id': ['AB-23473427','AB-99999'], 'feed': 16}, {'id': ['HA-4848231'], 'feed': 12}]
l2 = [{'id': ['AB-23473427'], 'feed': 14}, {'id': ['HA-4848231'], 'feed': 12}]

for elm2 in l2:
    for elm1 in l1:
        if elm2['feed'] == elm1['feed']:
            elm1['id'].extend(elm2['id'])
            break
    else:
        l1.append(elm2)

尝试一下。 这会将l1设置为[{'id': ['AB-23473427', 'AB-99999'], 'feed': 16}, {'id': ['HA-4848231', 'HA-4848231'], 'feed': 12}, {'id': ['AB-23473427'], 'feed': 14}]