1

I trying to merge 2 dictionaries which have the ability to create nested dictionaries and had an incorrect result.
Code example.

def merge_two_dicts(x, y):
    z = x.copy()
    z.update(y)
    return z

def create_dict(l, val):
    d = {}
    for a in reversed(l):
        if d == {}:
            d = {a: val}
        else:
            d = {a: d}
    return d


test = "a.b.t.q"
test2 = "a.b.t.w"

list1 = test.split(".")
list2 = test2.split(".")
val1 = "test"
val2 = "test2"
dict1 = create_dict(list1, val1)
dict2 = create_dict(list2, val2)

merged_dict = merge_two_dicts(dict1, dict2)

print "Dict #1"
print dict1
print "========================"
print "Dict #2"
print dict2
print "========================"
print "Merged dict"
print merged_dict

And the actual result is.

Dict #1
{'a': {'b': {'t': {'q': 'test'}}}}
========================
Dict #2
{'a': {'b': {'t': {'w': 'test2'}}}}
========================
Merged dict
{'a': {'b': {'t': {'w': 'test2'}}}}

Expected:

{'a': {'b': {'t': {'q': 'test', 'w': 'test2'}}}}

How can I merge dictionaries like with without losing some items?

creedqq
  • 302
  • 4
  • 15

1 Answers1

0

Find the answer here

Thanks, all.

creedqq
  • 302
  • 4
  • 15