Search code examples
pythonpyyaml

Pyyaml, accessing dictionary in Python


I have some yaml I'm trying to access keys in python.

---
nodes:
-
  AAAA: AAAA
  BBBB: BBBB
  CCCC: CCCC
  DDDD:
    AAAA: AAAA
    BBBB: AAAA
    CCCC: CCCC
-
  AAAA: AAAA
  BBBB: BBBB
  CCCC: CCCC
  DDDD:
    AAAA: AAAA
    BBBB: AAAA
    CCCC: CCCC

I'm trying to access using the following python format.

import yaml
filepath = "report.yml"
audit = yaml.load(open(filepath))

audit['nodes']['DDDD'].items() 

but I get the following error.

print audit['nodes']['DDDD'].items() TypeError: list indices must be integers, not str

Whats i'm expetcting to see is a list of key/values returned under DDDD

Obviously, I'm mixing up lists and dicts, but I don't quite see how... is it the yaml, python or my understanding of how pyyaml nests dicts in dicts?


Solution

  • You have a list of nodes. Use a for-loop to access each node and then the required values

    Ex:

    import yaml
    filepath = filename
    audit = yaml.load(open(filepath))
    
    for node in audit['nodes']:
        print( node['DDDD'].items() )
    

    Output:

    [('AAAA', 'AAAA'), ('CCCC', 'CCCC'), ('BBBB', 'AAAA')]
    [('AAAA', 'AAAA'), ('CCCC', 'CCCC'), ('BBBB', 'AAAA')]