I have yaml keys in the form “a.b.c.d” but my yaml file is in the format:
a: b: c: e:"world" d: "hello" e: f: g: "sample" h: 1
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:
a: b: c: d: "hello" e: f: g: "sample" h: 1
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?
keys = ["a","b","c","e"] yaml_dict = { ... } # some nested dict last_dict = yaml_dict # search node to delete for key in keys[:-1]: last_dict = last_dict.get(key, None) if node is None: # key not found break if last_dict is not None and keys[-1] is in last_dict: del last_dict[keys[-1]] # delete last key from last dict # TODO: delete whole dict if the key was the only key on this level