0

I have two lists that I need to merge based on a column name that exists in both. The source is JSON. I'm not sure how to do this, I looked at How to merge multiple dicts with same key? but that one doesn't constrain anything.

Example:

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

ClausJP
  • 3
  • 2
  • Do you always want only 3 elements in the dictionary? Can you also add the expected O/P when there are no duplicate elements? – JacksonPro Jan 15 '21 at 03:50
  • I have some 500+ rows but yes the columns would always be the same. But I was hoping to find a way to add new columns where a reference column compares which order the elements would be added. I can do it an MS Excel, but having issues here – ClausJP Jan 15 '21 at 19:08
  • I have an answer. I am not sure whether that is correct. Do you mind checking it? – JacksonPro Jan 16 '21 at 01:45
  • @JacksonPro where would I see this answer? – ClausJP Jan 18 '21 at 09:58

1 Answers1

0

Here try this.

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))


JacksonPro
  • 3,135
  • 2
  • 6
  • 29