很抱歉,如果这是一个愚蠢的问题,我对yaml配置(一般是+配置)非常陌生,并且一切都有些混乱。我有一个这样的文件:
hosts:
- hostid: 43842
tag: "name"
items:
port: "some port"
in: 2342124
out: 2349334
- hostid: 24586
tag: "..."
以此类推。此配置适用于我的项目(使用python制作),但是我想在“ items”下添加更多端口值,并让它们具有自己的输入/输出坐标。我似乎找不到合适的格式。有什么方法可以解决这个问题?预先谢谢你。
答案 0 :(得分:0)
看起来items
是类型dict
,这意味着您不能拥有相同的键,或者一遍又一遍地覆盖值。您需要的是list
中的dict
。
我们可以使用pyyaml
(pip install pyyaml
)来完成此操作。这是一个例子
import yaml
contents = """
hosts:
- hostid: 43842
tag: "name"
items:
port: "some port"
in: 2342124
out: 2349334"""
# cook the data a little to make items a list instead of a dict
data = yaml.full_load(contents)
for d in data.get('hosts'):
d['items'] = [d.get('items')]
# modify whatever we are interested in
for host in data.get('hosts'):
if host.get('hostid') == 43842:
host['items'].append({
'port': 'another port',
'in': 12345,
'out': 12345
})
# show our modifications
print(yaml.dump(data))
此打印:
hosts:
- hostid: 43842
items:
- in: 2342124
out: 2349334
port: some port
- in: 12345
out: 12345
port: another port
tag: name
答案 1 :(得分:0)
您可以在项目内包含对象列表。多个端口。
hosts:
- hostid: 43842
tag: "name"
items:
- port: "some port"
in: 2342124
out: 2349334
- port: "some other port"
in: 2342124
out: 2349334
或者,如果您希望在同一端口下有多个输入/输出值,则可以在某些属性下添加列表,例如数据
hosts:
- hostid: 43842
tag: "name"
items:
port: "some port"
data:
- in: 2342124
out: 2349334
- in: 2342124
out: 2349334