0

I have two dictionaries of tuples, and in the end I need one dictionary with the tuples merged. I am wondering what is the most efficient way to achieve this task.

dict1 = {'a': (1, 2, 3),
         'b': (2, 3, 4),
         'c': (3, 4, 5)
         'd': (6)}

dict2 = {'a': (2, 1),
         'b': (3),
         'c': (5, 4)}

merged = merge_function(dict1, dict2)

Expected result:

merged = {'a': (1, 2, 3, 2, 1),
          'b': (2, 3, 4, 3),
          'c': (3, 4, 5, 4, 3),
          'd': (6)}
Nexon
  • 326
  • 1
  • 11
  • What if the key does not exist in one of them? Is it ignored (inner join) or added anyway (outer)? – cs95 Jan 09 '19 at 10:36
  • As a side note those are **tuples**, not lists. – meowgoesthedog Jan 09 '19 at 10:37
  • it's added, so outer join – Nexon Jan 09 '19 at 10:39
  • ok I'll edit the question – Nexon Jan 09 '19 at 10:40
  • @coldspeed, Are we sure this is a dup? Having tuples instead of lists is a subtle (but important) distinction. Needs clarification from OP to make sure we do indeed have tuples. (I was going to use `defaultdict` + `chain` to avoid creating new tuples each time.) – jpp Jan 09 '19 at 10:42
  • yes in fact it's about the tuples, not lists, sorry for that still new to python – Nexon Jan 09 '19 at 10:45
  • 1
    @Nexon, In that case, note `(3)` is an integer, not a tuple, the tuple would be `(3,)`. I would advise you try the marked dup anyway and update your question with what problem you found. – jpp Jan 09 '19 at 10:49
  • @jpp Perhaps, although you can argue the same optimization is possible with list concatenation in the dupe. Consider adding an itertools solution there as well. – cs95 Jan 09 '19 at 10:51
  • @Nexon, I've added an answer to the marked dup which you might find helpful – jpp Jan 09 '19 at 11:13
  • @jpp yeah, thanks, it worked! – Nexon Jan 09 '19 at 12:18

0 Answers0