简体   繁体   English

python - 更新字典的值

[英]python - Update value of a dict

The following code reads from a YAML file, and converts into key-value pair.以下代码从 YAML 文件中读取,并转换为键值对。 Saving the dictionary into "config" variable.将字典保存到“config”变量中。

To do - Update the "name" field of "key4" from "Name2" to "newName".要做 - 将“key4”的“name”字段从“Name2”更新为“newName”。

from yaml import load as yload, YAMLError, SafeLoader

YAML_FILE = "test.yaml"

def toTest(): 
  fp = getFile(path.dirname(__file__), YAML_FILE)
  config = yload(fp.read(), Loader=SafeLoader)
  config.setdefault(conf.get("key1").get("key2").get("key4").get("name"), "newName")

def getFile(filepath, filename) -> TextIO:
    filepathR = open("%(path)s/%(filename)s" % {
        "path": filepath,
        "filename": filename
    }
    return filepathR

test.yaml -测试.yaml -

key1:
  key2:
    key3:
      name: Name1
      address: Add1
    key4:
      name: Name2
      address: Add2

setdefault doesn't seem to work. setdefault 似乎不起作用。

What would be the right way to update this value?更新此值的正确方法是什么?

You can set a new value with您可以设置一个新值

config['key1']['key2']['key4']['name'] = 'newName'

provided all such keys are present in the dictionary前提是所有这些键都存在于字典中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM