1

I have two dictionnaries loaded from config files, formatted like this: {key: (value, files_name)}

With files_name: the files where i can find this value.

For example:

dict_1 = {'a': ({'b': ({'c': (1, ['file_1'])}, ['file_1'])}, ['file_1'])}
dict_2 = {'a': ({'b': ({'c': (2, ['file_2'])}, ['file_2'])}, ['file_2'])}

I want to merge them together, and make a concatenation of the files names list.

So basically, following the example above, the output should be:

{'a': ({'b': ({'c': (1, ['file_1', 'file_2'])}, ['file_1', 'file_2'])}, ['file_1', 'file_2'])}
Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
Viak
  • 59
  • 6

2 Answers2

1

With recursion it can be done with dictionaries of any complexity, provided that the structure and the keys are the same in both dictionaries.

def mergedict(dd1, dd2):
    dict_res = {}
    for key, val in dd1.items():
        if isinstance(val[0], dict):
            dict_res[key] = (mergedict(val[0], dd2[key][0]), val[1] + dd2[key][1])
        else:
            dict_res[key] = (val[0], val[1] + dd2[key][1])
    return dict_res

So if you do:

rr = mergedict(dict_1, dict_2)
print(rr)

with your dicts you get:

{'a': ({'b': ({'c': (1, ['file_1', 'file_2'])}, ['file_1', 'file_2'])}, ['file_1', 'file_2'])}

which is your expected output.

Valentino
  • 7,291
  • 6
  • 18
  • 34
  • This output is exactly what I need for this case. But what if the keys are not the same in both dictionaries ? for example: dict_1 = `{'a': ({'b': ({'c': (1, ['my_file'], []), 'd': (3, ['my_file'], [])}, ['my_file'], [])}, ['my_file'], [])} ` dict_2 = `{'a': ({'x': ('we', ['my_file'], []), 'c': (2, ['my_file'], [])}, ['my_file'], []), 'e': ({'f': (22, ['my_file'], []), 'ok': ('ok', ['my_file'], [])}, ['my_file'], [])} ` – Viak Feb 08 '19 at 10:33
  • What do you want in that case? An intersection of the common keys or an union? – Valentino Feb 08 '19 at 12:23
  • I would like something like this: `res = {'a': ({'b': ({'c': (1, ['file_1']}, file), 'x': (value, file)}, file)}` – Viak Feb 08 '19 at 13:11
0

I believe this is close to what you're looking for. Though this is an assumption without seeing your code:

dict_1 = {'a': ({'b': ({'c': (1, ['file_1'])}, ['file_1'])}, ['file_1'])}
dict_2 = {'a': ({'b': ({'c': (2, ['file_2'])}, ['file_2'])}, ['file_2'])}

ds = [dict_1, dict_2]

d = {}

for k in dict_1.iterkeys():
    d[k] = tuple(d[k] for d in ds)

print d

>> {'a': (({'b': ({'c': (1, ['file_1'])}, ['file_1'])}, ['file_1']),
  ({'b': ({'c': (2, ['file_2'])}, ['file_2'])}, ['file_2']))}
Brandon Bailey
  • 781
  • 6
  • 12