Home > Back-end >  Python merge multiple dicts with common keys, generating new keys for the respective source dict
Python merge multiple dicts with common keys, generating new keys for the respective source dict

Time:07-30

Is there an elegant way in python to go from

d1 = {"key1": ["a", "b"], "key2": ["c", "d"]}  
d2 = {"key1": ["e", "f"], ...} 

to:

dd =
[
   { "old_key": "key1",
     "d1_key": ["a", "b"],
     "d2_key": ["e", "f"]
   },
   { "old_key": "key2",
     "d1_key": ["c", "d"]
   }
]

I'm not fussed if there is a d2_key: "" if there exists no old_key in d2

EDITED: from pseudo code

CodePudding user response:

Courtesy of a very helpful colleague I think have a solution I think solves it. The union operation is something I have never used/considered before.

all_keys = (d1.keys() | d2.keys())
dd = []
for key in all_keys:
    dd.append({"old_key": key,
               "d1_key": d1.get(key, ""),
               "d2_key": d2.get(key, "")})

CodePudding user response:

You can do something like this:

dd = list()
for k, v in d1.items():
    temp_dict = dict()
    temp_dict["old_key"] = k
    temp_dict["d1_" k] = v
    if k in d2.keys():
        temp_dict["d2_" k] = d2[k]
    dd.append(temp_dict)

Beware that this will ignore all the keys that are in d2 but not in d1 for if they are neccesary you can also add this for loop afterwards:

for k, v in d2.items():
    temp_dict = dict()
    if k not in d1.keys():
        temp_dict["d2_"   k] = d2[k]
    dd.append(temp_dict)
  • Related