通过比较python中的示例JSON来填充丢失的键

发布于 2025-02-09 12:02:22 字数 1777 浏览 1 评论 0 原文

我想首先合并两个词典,这意味着第一个字典不会丢失其先前的值,并且只有丢失的键值被添加到第一个值中。

Original =  {key1: { key2:[{ key3: y1 , key5: z1 , key6 [{key7: n1}]}]}}

Example = {key1: { key2:[{ key3: None , key4: None ,key5: None , key6 [{key7: None,key8:None}]}]}}

def update2(final, first):
 for k, v in first.items():
    if isinstance(v, str):
        final[k] = v
    elif k in final:
        if isinstance(final[k], dict):
            final[k].update2(first[k])
        else:
            final[k] = first[k]
    else:
        final[k] = first[k]

    final_json = update2(Example['key1'], Original['key1'])
    print(final_json)

#returns only Original not appended output

    def update3(right,left):
        d = dict()
        for key,val in left.items():
         d[key]=[val]
        for key,val in right.items():
         if key not in d.keys():
          d[key].append(val)
         else:
          d[key]=[val]

    final_json = update3(Example['key1'], Original['key1'])
    print(final_json) #returns None

预期输出:

{key1:{key2:[{key3:y1,key4:none,key5:z1,ke1,key6 [{key7:n1,key8:none}]}}}}}}}}}}}}}}}}}}}}}}

}它必须在多个层面上迭代。

根据JSON Schema的设置默认值

” https://stackoverflow.com/questions/55694862/how-to-to-merge-two-dictionaries基于-n-key-beke-but-include-missing-missing-key-key-key-vorues-in-pyt"> in> wought"> wough>在键上,但在python中包括丢失的密钥值?

合并两个词典并坚持第一个字典的值

我的目标是在示例文件中添加丢失键的默认值。我是初学者到python。

I want merge two dictionaries first over second, meaning the first dictionary doesn't lose its previous values and only the missing key values are added into first.

Original =  {key1: { key2:[{ key3: y1 , key5: z1 , key6 [{key7: n1}]}]}}

Example = {key1: { key2:[{ key3: None , key4: None ,key5: None , key6 [{key7: None,key8:None}]}]}}

def update2(final, first):
 for k, v in first.items():
    if isinstance(v, str):
        final[k] = v
    elif k in final:
        if isinstance(final[k], dict):
            final[k].update2(first[k])
        else:
            final[k] = first[k]
    else:
        final[k] = first[k]

    final_json = update2(Example['key1'], Original['key1'])
    print(final_json)

#returns only Original not appended output

    def update3(right,left):
        d = dict()
        for key,val in left.items():
         d[key]=[val]
        for key,val in right.items():
         if key not in d.keys():
          d[key].append(val)
         else:
          d[key]=[val]

    final_json = update3(Example['key1'], Original['key1'])
    print(final_json) #returns None

Expected output:

{key1: { key2:[{ key3: y1 , key4: None ,key5: z1 , key6 [{key7: n1,key8:None}]}]}}

I have referred many stackoverlfow posts but nothing is working since it has to be iterated at multiple levels.

Set default values according to JSON schema automatically

how to merge two dictionaries based on key but include missing key values in python?

Merge two dictionaries and persist the values of first dictionaries

My goal is to add default values for missing keys from example file.I am beginner to Python.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

遥远的绿洲 2025-02-16 12:02:22

尝试在以下步骤中递归处理。

  1. 确定键是否存在,如果不是,则直接分配值,如果是的,请转到下一步
  2. 确定值字典的类型
  • :递归呼叫
  • 列表:通过内容迭代并为每个项目进行递归呼叫
  • :直接分配如果原始词典不是

这样的,那么

def update(orignal, addition):
    for k, v in addition.items():
        if k not in orignal:
            orignal[k] = v
        else:
            if isinstance(v, dict):
                update(orignal[k], v)
            elif isinstance(v, list):
                for i in range(len(v)):
                    update(orignal[k][i], v[i])
            else:
                if not orignal[k]:
                    orignal[k] = v




Original =  {
    "key1": {
        "key2":[
            { "key3": "y1" ,
              "key5": "z1" ,
              "key6": [
                {"key7": "n1"}
              ]
            }
        ]
    }
}

Example = {
    "key1": {
        "key2":[
            {
                "key3": None ,
                "key4": None ,
                "key5": None ,
                "key6": [
                    {"key7": None,"key8":None}
                ]
            }
        ]
    }
}
print("Original: ", Original)
print("Addition: ", Example)
update(Original, Example)
print("Merge: ", Original)

# Original:  {'key1': {'key2': [{'key3': 'y1', 'key5': 'z1', 'key6': [{'key7': 'n1'}]}]}}
# Addition:  {'key1': {'key2': [{'key3': None, 'key4': None, 'key5': None, 'key6': [{'key7': None, 'key8': None}]}]}}
# Merge:  {'key1': {'key2': [{'key3': 'y1', 'key5': 'z1', 'key6': [{'key7': 'n1', 'key8': None}], 'key4': None}]}}


Try processing it recursively, in the following steps.

  1. determine if the key is present, if not, assign the value directly, if so go to the next step
  2. determine the type of the value
  • Dictionary: recursive call
  • List: iterate through the contents and make a recursive call for each item
  • Other: assign directly if the original dictionary is not None

like this:

def update(orignal, addition):
    for k, v in addition.items():
        if k not in orignal:
            orignal[k] = v
        else:
            if isinstance(v, dict):
                update(orignal[k], v)
            elif isinstance(v, list):
                for i in range(len(v)):
                    update(orignal[k][i], v[i])
            else:
                if not orignal[k]:
                    orignal[k] = v




Original =  {
    "key1": {
        "key2":[
            { "key3": "y1" ,
              "key5": "z1" ,
              "key6": [
                {"key7": "n1"}
              ]
            }
        ]
    }
}

Example = {
    "key1": {
        "key2":[
            {
                "key3": None ,
                "key4": None ,
                "key5": None ,
                "key6": [
                    {"key7": None,"key8":None}
                ]
            }
        ]
    }
}
print("Original: ", Original)
print("Addition: ", Example)
update(Original, Example)
print("Merge: ", Original)

# Original:  {'key1': {'key2': [{'key3': 'y1', 'key5': 'z1', 'key6': [{'key7': 'n1'}]}]}}
# Addition:  {'key1': {'key2': [{'key3': None, 'key4': None, 'key5': None, 'key6': [{'key7': None, 'key8': None}]}]}}
# Merge:  {'key1': {'key2': [{'key3': 'y1', 'key5': 'z1', 'key6': [{'key7': 'n1', 'key8': None}], 'key4': None}]}}


回首观望 2025-02-16 12:02:22

我以为没有列表,并且不希望将键中的键添加到示例中。我不确定这是您要寻找的答案,但这是一个建议。

def f(base: dict, data: dict):
    keys = base.keys() & data.keys()
    for key in keys:
        if isinstance(base[key], dict):
            f(base[key], data[key])            
        elif base[key] is None:
            base[key] = data[key]

Python

>>> data = {"key1": {"key2": {"key3": "y1", "key5": "z1", "key6": {"key7": "n1"}}}}
>>> base = {"key1": {"key2": {"key3": "a1", "key4": None, "key5": None, "key6": {"key7": None, "key8": None}}}}
>>> f(base, data)
>>> print(base)
{'key1': {'key2': {'key3': 'a1', 'key4': None, 'key5': 'z1', 'key6': {'key7': 'n1', 'key8': None}}}}

I assumed that there was no list and that it was not desired that a key present in Original but not present in Example be added to Example. I'm not sure this is the answer that you are looking for, but here is a proposal.

def f(base: dict, data: dict):
    keys = base.keys() & data.keys()
    for key in keys:
        if isinstance(base[key], dict):
            f(base[key], data[key])            
        elif base[key] is None:
            base[key] = data[key]

python

>>> data = {"key1": {"key2": {"key3": "y1", "key5": "z1", "key6": {"key7": "n1"}}}}
>>> base = {"key1": {"key2": {"key3": "a1", "key4": None, "key5": None, "key6": {"key7": None, "key8": None}}}}
>>> f(base, data)
>>> print(base)
{'key1': {'key2': {'key3': 'a1', 'key4': None, 'key5': 'z1', 'key6': {'key7': 'n1', 'key8': None}}}}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文