<> Question introduction

Sometimes we need to merge two dictionaries , We need the same key value , Merge into one list .

<> code
dic_a = {"key1":1,"key5":2} dic_b = {"key1":3,"key4":4} print(" Dictionary before merging 1 yes {}".
format(dic_a)) print(" Dictionary before merging 2 yes {}".format(dic_b)) # What is the goal "key2":[2,3]
result_dic= {} ''' Core ideas : 1: Traverse dictionary 1 And dictionaries 2 Every key of 2: If the keys of two dictionaries are the same , The key of the new dictionary is assigned an empty list
Then the empty list adds the dictionary in turn 1 And dictionaries 2 Value of , Then assign the final value to the original dictionary 3: If the keys of two dictionaries are different , Then the key value pairs are added to the new list respectively ''' 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))
<> result

Technology