2

I am new to Python so please bear with me. I am trying to figure out how to loop through a set of values in a YAML file. The file is parsed using PyYAML and then would need to be fed into the loop. Here is some YAML for example:

dohicky.yml

---
#Example file
dohicky:
  "1":
    Stuff:
      - Data
      - Data
    Morestuff:
      - Data
      - Data
  "2":
    Stuff:
      - Data
      - Data
    Morestuff:
      - Data
      - Data
  "n":
    - Etc

First, I am pulling the contents of the YAML out.

import yaml
f = open('dohicky.yml')
dohicky = yaml.safe_load(f)
f.close()

Now I just need either a for loop or a while loop to iterate through each numbered "id" under "dohicky".

for x in xrange(1, 2):

So obviously this would work, but is staticly defined for only 2 elements. Not sure how for example:

"do while" id = dohicky["dohicky"]["x"] is true. #Not code, just concept!

The other problem I am immediately running into is how to then create an object inside this loop. For example:

id(x) = dohicky(Pass other info from YAML to class) #Not code, just concept!

Unfortunately I am not familiar enough with Python yet (withPyYAML) to understand the syntax. Any help is MUCH appreciated!

* UPDATE * This is kinda sudo code, but you should understand what I am trying to do at least.

import yaml
f = open('dohicky.yml')
dohicky = yaml.safe_load(f)
f.close()

for x in dohicky["dohicky"]["x"]
        test = dohicky["dohicky"]["1"]["Stuff"]
        print test

In this test, I am just printing the output of "Stuff", but in reality, I need to create an object using that data.

Atomiklan
  • 5,164
  • 11
  • 40
  • 62

1 Answers1

4

You can use the following code to iterate through each numbered "id" under "dohicky":

for dohicky_id in dohicky['dohicky']:
    stuff = dohicky['dohicky'][dohicky_id]['Stuff']

In this case, the stuff is a list of Data dicts. If you can't, for whatever reasons, to work with the dictionary, and you want to convert the Data dicts into objects, you can do this by looking the following question: Convert Python dict to object?

Community
  • 1
  • 1
Alexander Fedotov
  • 955
  • 12
  • 19