Skip to content
Advertisement

Merge multiple key in dictionary with same values inside an array

I need to merge three dictionaries with array values into a single dict based on if they have same values inside the array. The dictionaries is like this:

data = {
'A1':['Cheese','Cupcake', 'Salad','Sandwich'],
'A2':['Cheese','Cupcake', 'Pasta','Pudding'],
'A3':['Pudding','Pasta', 'Salad','Sandwich']
}

Then, the output would be like this:

{
   'A1,A2':['Cheese','Cupcake']
   'A1,A3':['Salad', 'Sandwich']
   'A2,A3':['Pudding','Pasta']
}

I’ve tried this:

tmp = {}
for key, value in data.items():
  if value in tmp:
    tmp[value].append(key)
  else:
    tmp[value] = [ key ]
print(tmp)

But it only works if the values isn’t a list or array. Any solution?

Advertisement

Answer

Given you use case, you could use itertools.combinations and set intersection:

data = {
'A1':['Cheese','Cupcake', 'Salad','Sandwich'],
'A2':['Cheese','Cupcake', 'Pasta','Pudding'],
'A3':['Pudding','Pasta', 'Salad','Sandwich']
}


from itertools import combinations

out = {f'{a},{b}': list(set(data[a]).intersection(data[b]))
       for a,b in combinations(data, 2)}

output:

{'A1,A2': ['Cupcake', 'Cheese'],
 'A1,A3': ['Sandwich', 'Salad'],
 'A2,A3': ['Pasta', 'Pudding']}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement