首页 > 解决方案 > 比较列相等时如何追加列

问题描述

我有两个列表需要根据两者中存在的列名进行合并。源是 JSON。我不知道该怎么做,我看了如何用相同的键合并多个字典?但那不限制任何东西。

例子:

dict1 = {"a": 3, 'b': 4}
dict2 = {"a": 3, 'c': 5}
dict3 = {"a": 1, 'b': 2}
dict4 = {"a": 1, 'c': 8}

dict_result = [{"a": 3, 'b': 4, 'c': 5},{"a": 1, 'b': 2, 'c': 8}]

BR

标签: pythonlistdictionarymerge

解决方案


这里试试这个。

dict1 = {"a": 3, 'b': 4}
dict2 = {"a": 3, 'c': 5}
dict3 = {"a": 1, 'b': 2}
dict4 = {"a": 1, 'c': 8}

def merge_dictionary(*args):
    dictionary = []
    dict_result=[]
    app_index = 0 # append index

    for dic in (args):
        for item, value in dic.items():
            if [item, value] not in dictionary:
                dictionary.append([item, value])


    for index, x in enumerate(dictionary):
        
        if index%3==0: 
            dict_result.append({x[0]:x[1]})
            app_index = index
       
        else:
            dict_result[app_index//3].update({x[0]:x[1]})

    return dict_result

print(merge_dictionary(dict1, dict2, dict3, dict4))



推荐阅读