Home > OS >  Merge 2 dictionaries based on specific features
Merge 2 dictionaries based on specific features

Time:09-29

With 2 json file I am trying to merge certain features of one into the other. I converted the json into dictionaries I am trying to merge features from 1 dictionary into another. However I want specific features of one dictionary to merege with the other but not overwrite the initial values

Dictionary A: [{a:1,b:2,f:10},{a:2,b:4,f:10}]
Dictionary B: [{f:1,g:1,k:1},{f:2,g:2,k:1}]

Desired:

Dictionary C:[{a:1,b:2,f:10,g:1,k:1},{a:2,b:4,f:10,g:2,k:1}]
Loop through all dictionaries simultaneously
 for x,y in zip(A,B):
     x["g"]= y["g"]
     x["k"]= y["k"]


CodePudding user response:

You can iterate using zip then combine the dictionaries and filter out the keys that you don't want, you can use comprehension:

# Python 3.9 
>>> [y|x for x,y in zip(A, B)]

# output:
[{'f': 10, 'g': 1, 'k': 1, 'a': 1, 'b': 2}, 
{'f': 10, 'g': 2, 'k': 1, 'a': 2, 'b': 4}]

CodePudding user response:

This will preserve the order and not overwrite any duplicate keys in A.

lst_a =  [{'a':1,'b':2,'f':10},{'a':2,'b':4,'f':10}]
lst_b = [{'f':1,'g':1,'k':1},{'f':2,'g':2,'k':1}]

lst_c = []
    
for dict_a,dict_b in zip(lst_a,lst_b):
    dict_b = {k:v for k,v in dict_b.items() if k not in dict_a}
    lst_c.append(dict_a | dict_b)

print(lst_c)
  • Related