从DeepDiff resu构造python dict

2024-05-13 23:16:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个DeepDiff结果,它是通过比较两个JSON文件获得的。我必须从deepdiff结果构造一个python字典,如下所示。在

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}

如何做到这一点?在


Tags: 文件jsondictionary字典rootsparkpollttl
2条回答

也许还有更好的方法。但是您可以解析返回的字符串,并将一个新字典与您想要的结果链接在一起。在

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}}

简单的回答, 在python中有一个名为dictdifference函数的内部构建。你能试试这个吗。在

$ pip install dictdiffer

示例:

^{pr2}$

参考文献: DictDiffer

相关问题 更多 >