python iterate yaml and filter result

Question:

I have this yaml file

data:
  - name: acme_aws1
    source: aws
    path: acme/acme_aws1.zip
  - name: acme_gke1
    source: gke
    path: acme/acme_gke1.zip
  - name: acme_oci
    source: oci
    path: acme/acme_oci1.zip
  - name: acme_aws2
    source: aws
    path: acme/acme_aws2.zip
  - name: acme_gke2
    source: gke
    path: acme/acme_gke2.zip
  - name: acme_oci2
    source: oci
    path: 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.

Asked By: hare krshn

||

Answers:

import yaml


# Read the file.
content = yaml.safe_load('your_file.yaml')

# Get rid of 'gke' elements.
not_gke_sources = [block for block in content if block.source != 'gke']

# Iterate over to access all 'path's.
for block in not_gke_sources:
    path = block.path
    # Some actions.
Answered By: Filipp Aleksandrov

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_aws1
  source: aws
  path: acme/acme_aws1.zip
- name: acme_gke1
  source: gke
  path: acme/acme_gke1.zip
- name: acme_oci
  source: oci
  path: acme/acme_oci1.zip
- name: acme_aws2
  source: aws
  path: acme/acme_aws2.zip
- name: acme_gke2
  source: gke
  path: acme/acme_gke2.zip
- name: acme_oci2
  source: oci
  path: 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’}]

Answered By: Alexey Larionov
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.