I have yaml keys in the form “a.b.c.d” but my yaml file is in the format:
JavaScript
x
11
11
1
a:
2
b:
3
c:
4
e:"world"
5
d: "hello"
6
e:
7
f:
8
g: "sample"
9
h: 1
10
11
I want to delete “a.b.c.e” here and I have around 300 rows of yaml keys in similar format any idea on how to delete the keys?
I know about the del function in ruamel.yaml if it will be possible integrate.
Like Lets say I delete “a.b.c.e”
the desired output:
JavaScript
1
11
11
1
a:
2
b:
3
c:
4
d: "hello"
5
e:
6
f:
7
g: "sample"
8
h: 1
9
10
11
I know there is a problem with syntax. The actual yaml file has many more lines.
Advertisement
Answer
Yes but after splitting it I will get a list [“a”,”b”,”c”,”e”] and the format for key deletion would be del d[“a”][“b”][“c”][“e”] I do not know how to convert the list into that statement because not all the keys are of same length some are of form “a.b.c.d.e.f”.That is the problem I am facing.
something like this?
JavaScript
1
16
16
1
keys = ["a","b","c","e"]
2
yaml_dict = { } # some nested dict
3
4
last_dict = yaml_dict
5
6
# search node to delete
7
for key in keys[:-1]:
8
last_dict = last_dict.get(key, None)
9
if node is None:
10
# key not found
11
break
12
13
if last_dict is not None and keys[-1] is in last_dict:
14
del last_dict[keys[-1]] # delete last key from last dict
15
# TODO: delete whole dict if the key was the only key on this level
16