gpt4 book ai didi

python - 从 DeepDiff 结果构造 python 字典

转载 作者:太空宇宙 更新时间:2023-11-03 10:51:26 25 4
gpt4 key购买 nike

我有一个 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}

如何实现?

最佳答案

可能有更好的方法来做到这一点。但您可以解析返回的字符串,并将新字典与您想要的结果链接在一起。

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 - 从 DeepDiff 结果构造 python 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49611771/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com