简体   繁体   中英

python - Update value of a dict

The following code reads from a YAML file, and converts into key-value pair. Saving the dictionary into "config" variable.

To do - Update the "name" field of "key4" from "Name2" to "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 -

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

setdefault doesn't seem to work.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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