简体   繁体   中英

Removing key value pair from yaml dictionary in python

We would like to remove the key and the values from a YAML file using python, for example

- misc_props:
  - attribute: tmp-1
    value: 1
  - attribute: tmp-2
    value: 604800
  - attribute: tmp-3
    value: 100
  - attribute: tmp-4
    value: 1209600
  name: temp_key1
  attr-1: 20
  attr-2: 1
- misc_props:
  - attribute: tmp-1
    value: 1
  - attribute: tmp-2
    value: 604800
  - attribute: tmp-3
    value: 100
  - attribute: tmp-4
    value: 1209600
  name: temp_key2
  atrr-1: 20
  attr-2: 1

From the above example we would like to delete the whole bunch of property and where key name matches the value, for example if we want to delete name: temp_key2 the newly created dictionary after delete will be like below:-

- misc_props:
  - attribute: tmp-1
    value: 1
  - attribute: tmp-2
    value: 604800
  - attribute: tmp-3
    value: 100
  - attribute: tmp-4
    value: 1209600
  name: temp_key1
  attr-1: 20
  attr-2: 1

It is not sufficient to delete a key-value pair to get your desired output.

import sys
import ruamel.yaml


yaml = ruamel.yaml.YAML()
with open('input.yaml') as fp:
    data = yaml.load(fp)
del data[1]['misc_props']
yaml.dump(data, sys.stdout)

as that gives:

- misc_props:
  - attribute: tmp-1
    value: 1
  - attribute: tmp-2
    value: 604800
  - attribute: tmp-3
    value: 100
  - attribute: tmp-4
    value: 1209600
  name: temp_key1
  attr-1: 20
  attr-2: 1
- name: temp_key2
  atrr-1: 20
  attr-2: 1

What you need to do is delete one of the items of the sequence that is the root of the YAML structure:

del data[1]
yaml.dump(data, sys.stdout)

which gives:

- misc_props:
  - attribute: tmp-1
    value: 1
  - attribute: tmp-2
    value: 604800
  - attribute: tmp-3
    value: 100
  - attribute: tmp-4
    value: 1209600
  name: temp_key1
  attr-1: 20
  attr-2: 1

Did you try using the yaml module?

import yaml
with open('./old.yaml') as file:
    old_yaml = yaml.full_load(file)

#This is the part of the code which filters out the undesired keys
new_yaml = filter(lambda x: x['name']!='temp_key2', old_yaml) 

with open('./new.yaml', 'w') as file:
    documents = yaml.dump(new_yaml, file)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM