使用嵌套字典更新字典

时间:2021-04-10 13:10:27

标签: python json python-2.7

我有这个 json 文件用于通过 material -> refcolor 列出 size

{
    "base": {
        "ref": {
            "3021000": {
                "color": {
                    "bleu azur": {
                        "size": {
                            "01": "3021000-80300-01",
                            "13": "3021000-80300-13",
                            "12": "3021000-80300-12",
                            "36": "3021000-80300-36"
                        }
                    }
                }
            }
        },
        "customer_ref": {}
    }
}

通过程序,我会将 json 作为 dict 加载并搜索 dict 以尝试找到与大小值相对应的完整引用(用于材料 3021000 bleu azur 013021000-80300-01

它就像一个魅力,但现在,如果我有一个 material 与:ref=3021000color=blancsize=01,它不存在于字典中,所以我想插入缺失的 key - value: {"blanc": {"size": {"01": "corresponding full ref"}}}

我试过了:

ref = "3021000"
color = "blanc"
size = "01"
full_ref = "corresponding full ref"
missing_data = {ref: {"color": {color: {"size": {size: full_ref}}}}}
data["base"]["ref"] = missing_data

但它覆盖了字典;我想要的是更新字典,而不是覆盖它。

1 个答案:

答案 0 :(得分:1)

这个怎么样?

import json

d = {
    "base": {
        "ref": {
            "3021000": {
                "color": {
                    "bleu azur": {
                        "size": {
                            "01": "3021000-80300-01",
                            "13": "3021000-80300-13",
                            "12": "3021000-80300-12",
                            "36": "3021000-80300-36"
                        }
                    }
                }
            }
        },
        "customer_ref": {}
    }
}

ref = "3021000"
color = "blanc"
size = "01"
full_ref = "corresponding full ref"
missing_data = {color: {"size": {size: full_ref}}}
d["base"]["ref"][ref]["color"].update(missing_data)
print(json.dumps(d, indent=2))

输出:

{
  "base": {
    "ref": {
      "3021000": {
        "color": {
          "bleu azur": {
            "size": {
              "01": "3021000-80300-01",
              "13": "3021000-80300-13",
              "12": "3021000-80300-12",
              "36": "3021000-80300-36"
            }
          },
          "blanc": {
            "size": {
              "01": "corresponding full ref"
            }
          }
        }
      }
    },
    "customer_ref": {}
  }
}