I have this yaml file
data:- name: acme_aws1source: awspath: acme/acme_aws1.zip- name: acme_gke1source: gkepath: acme/acme_gke1.zip- name: acme_ocisource: ocipath: acme/acme_oci1.zip- name: acme_aws2source: awspath: acme/acme_aws2.zip- name: acme_gke2source: gkepath: acme/acme_gke2.zip- name: acme_oci2source: ocipath: acme/acme_oci2.zip
i want to filter out the data containing "source=gke" and for loop assign the value of path to variable., can any one please share how-to when using python with pyyaml as import module.
This code would do what you need, it just reads, and uses filter
standard function to return an iterable with the elements passing a condition. Then such elements are put into a new list
import yaml# for files you can use
# with open("data.yaml", "r") as file:
# yaml_data = yaml.safe_load(file)yaml_data = yaml.safe_load("""
data:
- name: acme_aws1source: awspath: acme/acme_aws1.zip
- name: acme_gke1source: gkepath: acme/acme_gke1.zip
- name: acme_ocisource: ocipath: acme/acme_oci1.zip
- name: acme_aws2source: awspath: acme/acme_aws2.zip
- name: acme_gke2source: gkepath: acme/acme_gke2.zip
- name: acme_oci2source: ocipath: acme/acme_oci2.zip
""")data = yaml_data['data']
filtered = list(filter(lambda x: x.get('source') == 'gke', data))
print(filtered)
It prints
[{'name': 'acme_gke1', 'source': 'gke', 'path': 'acme/acme_gke1.zip'}, {'name': 'acme_gke2', 'source': 'gke', 'path': 'acme/acme_gke2.zip'}]