使用嵌套字典更新字典

2024-05-22 22:40:02 发布

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

我使用这个json文件来列出materialby ref->colorsize

{
    "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 01的完整参考是3021000-80300-01

它就像一个符咒,但是现在,如果我有一个material带有:ref=3021000color=blancsize=01,它在dict中不存在,所以我想插入缺少的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

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


Tags: 文件refjsondatabasesizedictfull
1条回答
网友
1楼 · 发布于 2024-05-22 22:40:02

这个怎么样

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": {}
  }
}

相关问题 更多 >

    热门问题