如何更改yaml数据中的KEY

时间:2018-02-20 03:58:50

标签: python string dictionary yaml pyyaml

我在yaml文件下面作为模板。从另一个python程序我获取设备的名称,假设deviceB是新设备的名称。有人可以展示如何使用python替换deviceAdeviceB(替换映射KEY而不是VALUE)?

设备的占位符是固定的&没有变化。

Yaml数据:

testbed:
    name: "boot-ios"
devices:
    deviceA:
        type: IOS
        connections:
            defaults:
                 class: 
            a:
              protocol: telnet
              ip: 
              port: 

1 个答案:

答案 0 :(得分:0)

您可以读取数据,然后复制密钥,如:

代码:

import yaml

with open('file1', 'rU') as f:
    data = yaml.safe_load(f)

data['devices']['deviceB'] = data['devices']['deviceA']
del data['devices']['deviceA']

with open('file1', 'w') as f:
    yaml.dump(data, f)

结果:

devices:
  deviceB:
    connections:
      a: {ip: null, port: null, protocol: telnet}
      defaults: {class: null}
    type: IOS
testbed: {name: boot-ios}