Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Construct python dict from DeepDiff result

I have a DeepDiff result which is obtained by comparing two JSON files. I have to construct a python dictionary from the deepdiff result as follows.

json1 = {"spark": {"ttl":3, "poll":34}}
json2 = {"spark": {"ttl":3, "poll":34, "toll":23}, "cion": 34}

deepdiffresult = {'dictionary_item_added': {"root['spark']['toll']", "root['cion']"}}

expecteddict = {"spark" : {"toll":23}, "cion":34}

How can this be achieved?

like image 682
Srivignesh Avatar asked Apr 02 '18 12:04

Srivignesh


1 Answers

There is probably a better way to do this. But you can parse the returned strings and chain together a new dictionary with the result you want.

json1 = {"spark": {"ttl":3, "poll":34}}
json2 = {"spark": {"ttl":3, "poll":34, "toll":23}, "cion": 34}
deepdiffresult = {'dictionary_item_added': {"root['spark']['toll']", "root['cion']"}}
added = deepdiffresult['dictionary_item_added']

def convert(s, j):
    s = s.replace('root','')
    s = s.replace('[','')
    s = s.replace("'",'')
    keys = s.split(']')[:-1]
    d = {}
    for k in reversed(keys):
        if not d:
            d[k] = None
        else:
            d = {k: d}
    v = None
    v_ref = d
    for i, k in enumerate(keys, 1):
        if not v:
            v = j.get(k)
        else:
            v = v.get(k)
        if i<len(keys):
            v_ref = v_ref.get(k)
    v_ref[k] = v
    return d

added_dict = {}
for added_str in added:
    added_dict.update(convert(added_str, json2))

added_dict
#returns:
{'cion': 34, 'spark': {'toll': 23}}
like image 142
James Avatar answered Oct 08 '22 07:10

James