鉴于以下清单:
fruits:
- fruit: apple
color: red
texture: crunchy
shape: round
- fruit: grapefruit
color: yellow
taste: sour
- fruit: pear
color: yellow
如何使用items2dict过滤器更改为字典(如下)? 问题是有多个,并且值的数量是可变的
"{{ fruits | items2dict(key_name='fruit', value_name='??????') }}
预期结果:
fruits:
- apple:
color: red
texture: crunchy
shape: round
- grapefruit:
color: yellow
taste: sour
- pear:
color: yellow
items2dict()
函数不适合您的情况,但您可以使用以下简单方法:解释:
rows.split("\n")
从rows
多行字符串创建行列表[]
(列表理解)中的表达式2*" " + row if row.startswith(4*" ") else row
将从4-空间缩进开始的行缩进另一个2-空间缩进"\n".join()
将(修改过的)行列表转换回多行字符串李>输出:
我认为你可以做一些类似的事情:
相关问题 更多 >
编程相关推荐