Problem is introduced

Sometimes we need to merge two dictionaries, we need to merge the values of the same key into a list.

code

dic_a = {"key1":1."key5":2}

dic_b = {"key1":3."key4":4}
print("Pre-merge dictionary 1 is {}".format(dic_a))
print("Pre-merge dictionary 2 is {}".format(dic_b))
"Key2 ":[2,3]
result_dic = {}
If the keys of dictionaries 1 and 2 are the same, assign the key of the new dictionary to an empty list. Then add the values of dictionaries 1 and 2 to the empty list, and assign the last value to the original dictionary 3: If two dictionaries have different keys, the key-value pairs are separately added to the new list.
for k,v in dic_a.items():
    for m,n in dic_b.items():
        if k == m:
            result_dic[k] = []
            result_dic[k].append(dic_a[k])
            result_dic[k].append(dic_b[k])
            dic_a[k] = result_dic[k]
            dic_b[k] = result_dic[k]
        else:
            result_dic[k] = dic_a[k]
            result_dic[m] = dic_b[m]
    # if k in dic_b.keys():
        

print("The merged dictionary is {}.".format(result_dic))
Copy the code

The results of