I have multiple dicts/key-value pairs like this:
d1 = {key1: x1, key2: y1}
d2 = {key1: x2, key2: y2}
I want the result to be a new di
Assume that you have the list of ALL keys (you can get this list by iterating through all dictionaries and get their keys). Let's name it listKeys
. Also:
listValues
is the list of ALL values for a single key that you want
to merge.allDicts
: all dictionaries that you want to merge.result = {}
for k in listKeys:
listValues = [] #we will convert it to tuple later, if you want.
for d in allDicts:
try:
fileList.append(d[k]) #try to append more values to a single key
except:
pass
if listValues: #if it is not empty
result[k] = typle(listValues) #convert to tuple, add to new dictionary with key k