pythonyaml

Fetching nexted yaml file data in python


I need to loop through the main tag and fetch its subtag value in python scrip.

Sorry i am recently started using python script.

Chart1: 
    Slide: 1
    Top: 100
    Left: 100
    Width: 150
    Heigth: 150
Chart2: 
    Slide: 1
    Top: 100
    Left: 100
    Width: 150
    Heigth: 150
Chart3: 
    Slide: 1
    Top: 100
    Left: 100
    Width: 150
    Heigth: 150
import yaml 
from munch import Munch
#Read Yaml file

with open(r"C:\Users\ana\Chart\config.yaml", 'r') as stream:
    data_loaded = yaml.safe_load(stream)
configyaml = Munch(data_loaded)
print(data_loaded)
for index in range(3):
        Slidenumber = configyaml.Chart + index +.Slide
        STop = configyaml.Chart + index +.Top
        Sleft= configyaml.Chart + index +.Left
        print(Slidenumber)
        print(STop)
        print(Sleft)

Solution

  • You are trying to read a yaml file contaning three charts, and then loop through each chart to fetch specific values and print them out. However, there are a few issues in your code that are preventing the values from being displayed correctly.

    1. When using Munch library, you should access attributes with data.attribute instead of .attribute.
    2. The keys of the charts in your dictionary are strings (Chart1, Chart2, Chart3). To access them correctly, you must dynamically construct them using formatted strings: f"Chart{index}".
    3. The loop range must be adjusted to start from 1 and go up to 3. Using range(3) starts the loop from 0 to 2, which does not align with the required keys.
        for index in range(1, 4):
            chart_data = configyaml.get(f"Chart{index}")
            if chart_data:
                Slidenumber = char_data.get('Slide')
                STop = chart_data.get('Top')
                SLeft = chart_data.get('Left')
                print(f"Chart {index}: Slide={Slidenumber}, Top={STop}, Left={Sleft}")
    

    With these modifications, the code should work correctly, allowing you to loop through each chart, retrieve the desired values, and print them as intended.