-2

I have 2 dictionaries that I need to merge while extending the keys # to avoid overwrite. I cannot find a suitable solution. How can I do this ?

dic1 = {0: ['Café Replika', '252 Rue Rachel E, USA'], 1: ['Café Tuyo', '370 Rue Marie-Anne Est, USA'] }
dic2 = {0: ['Café Bistro', '4190 St Laurent , USA'], 1: ['Café Portugais', '4051 St Dominique St, USA']}

The output I need is :

finaldic = {0: ['Café Replika', '252 Rue Rachel E, USA'], 1: ['Café Tuyo', '370 Rue Marie-Anne Est, USA'], 2: ['Café Bistro', '4190 St Laurent , USA'], 3: ['Café Portugais', '4051 St Dominique St, USA']}

Thanks for the help

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Gil
  • 77
  • 1
  • 2
  • 8
  • 2
    Does this answer your question? [Merge dictionaries without overwriting values](https://stackoverflow.com/questions/12121417/merge-dictionaries-without-overwriting-values) – dspencer Mar 11 '20 at 04:23

2 Answers2

2

If I understand your example correctly, you want new keys assigned to the values of the two dictionaries in the merged result. You can do this using enumerate on the concatenation of the values from the two dictionaries:

dic1 = {0: ['Café Replika', '252 Rue Rachel E, USA'], 1: ['Café Tuyo', '370 Rue Marie-Anne Est, USA'] }
dic2 = {0: ['Café Bistro', '4190 St Laurent , USA'], 1: ['Café Portugais', '4051 St Dominique St, USA']}

merged = dict(enumerate((*dic1.values(),*dic2.values())))

result:

{
 0: ['Café Replika', '252 Rue Rachel E, USA'],
 1: ['Café Tuyo', '370 Rue Marie-Anne Est, USA'],
 2: ['Café Bistro', '4190 St Laurent , USA'],
 3: ['Café Portugais', '4051 St Dominique St, USA']
}
Alain T.
  • 40,517
  • 4
  • 31
  • 51
1

There will not be a built-in solution for what you describe, since there isn't a lot of logic to it. You seem to ignore the keys altogether, and treat the special dictionaries more like lists of lists.

You are asking for a function that takes:

def foo_dicts(x, y):
    ???

d1 = {0: ['a1', 'a2'], 1: ['b1', 'b2']}
d2 = {0: ['c1', 'c2'], 1: ['d1', 'd2']}
foo_dicts(d1, d2) == {0: ['a1', 'a2'], 1: ['b1', 'b2'], 2: ['c1', 'c2'], 3: ['c1', 'c2']}

If you actually had lists of lists, this would simply be +:

def foo_lists(x, y):
    return x + y

d1 = [['a1', 'a2'], ['b1', 'b2']]
d2 = [['c1', 'c2'], ['d1', 'd2']]
foo_lists(d1, d2) == [['a1', 'a2'], ['b1', 'b2'], ['c1', 'c2'], ['c1', 'c2']]

If you insist on keeping the indexed dictionaries, the simplest way is to enumerate them back into a dict after concatenating them:

def foo_dicts(x, y):
    return dict(enumerate(v for d in (x, y) for k, v in sorted(d.items()))
Cireo
  • 4,197
  • 1
  • 19
  • 24