I am looking for template as below. I tried dict2yaml which is not giving YAML format as below. Can someone help?
LEVEL_1:
LEVEL_2:
LEVEL_3: some_value
Another varient is
LEVEL_1:
LEVEL_2:
LEVEL_3:
- some_value1
- some_value2
- some_value3
CodePudding user response:
Here's a good example where Tcl's type system is not helpful to you. Any list with an even number of items could be considered a dict.
For example:
set nested_dict {key1 {key2 {x y}}}
is y
the value of a dict with three nested keys or is {x y}
the value of a dict with two nested keys?
The yaml::dict2yaml
function only works for simple dicts with no nested keys.
One possibility is to convert your nested dict into a "huddle" https://wiki.tcl-lang.org/page/huddle and then use yaml::huddle2yaml
.
It might be simpler to just iterate over the nested keys and handle indenation yourself. This is assuming you know the structure of the nested dict.
set nested_dict {key1 {key2 {x y}}}
dict for {k1 d1} $nested_dict {
puts "$k1:"
dict for {k2 d2} $d1 {
puts " $k2:"
dict for {k3 val} $d2 {
puts " $k3: $val"
}
}
}
which prints out:
key1:
key2:
x: y
An example with huddles:
package require huddle
package require yaml
set MyHuddle [huddle create]
huddle set MyHuddle LEVEL_1 [huddle create]
huddle set MyHuddle LEVEL_1 LEVEL_2 [huddle create]
huddle set MyHuddle LEVEL_1 LEVEL_2 LEVEL_3 [huddle list some_value1 some_value2 some_value3]
yaml::huddle2yaml $MyHuddle
which prints out:
---
LEVEL_1:
LEVEL_2:
LEVEL_3:
- some_value1
- some_value2
- some_value3
Please read the huddle man page carefully. huddle create
and huddle set
are very similar to dict create
and dict set
. However, I found that I needed to explicitly create a huddle below LEVEL_1 and LEVEL2 before I could set the LEVEL_3 key's value.