如何更改 yaml 数据中的 KEY
How to change a KEY in yaml data
我有以下 yaml 文件作为模板。我从另一个 python 程序中获取设备名称,假设 deviceB
是新设备的名称。有人可以展示如何使用 python 将 deviceA
替换为 deviceB
(替换映射 KEY 而不是 VALUE)吗?
设备的占位符是固定不变的。
Yaml 数据:
testbed:
name: "boot-ios"
devices:
deviceA:
type: IOS
connections:
defaults:
class:
a:
protocol: telnet
ip:
port:
你可以读入数据,然后像这样复制密钥:
代码:
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}
我有以下 yaml 文件作为模板。我从另一个 python 程序中获取设备名称,假设 deviceB
是新设备的名称。有人可以展示如何使用 python 将 deviceA
替换为 deviceB
(替换映射 KEY 而不是 VALUE)吗?
设备的占位符是固定不变的。
Yaml 数据:
testbed:
name: "boot-ios"
devices:
deviceA:
type: IOS
connections:
defaults:
class:
a:
protocol: telnet
ip:
port:
你可以读入数据,然后像这样复制密钥:
代码:
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}