Linked Questions

Popular Questions

Parsing through a yaml using python

Asked by At

I'm trying to make a tuple of 2 keys by reading a yaml.

structure looks like

abc:
 xyz:
  efg:
   fgh:
     a: b
  rty:
   ccc:
    - a_table: t0
      b_table: t1

zzz:
 xyz:
  efg:
   fgh:
     a: b
  rty:
   ccc:
    - a_table: t2
      b_table: t3
eee:
 xyz:
  efg:
   fgh:
     a: b
  rty:
   ccc:
    - a_table: t5
      b_table: t6
fff:
 xyz:
  efg:
   fgh:
     a: b
  rty:
   ccc:
    - a_table: t9
      b_table: t10

There are multiple entries within the yaml and structure always remain same. I want t0 and t1 to be grouped so that I know they part of one config in yaml. Sometime I may only get a_table and sometimes both.

What I have tried already: I have tried creating a generator to get the list of a_table and b_table separately but I'm unable to map both of them as they their lengths aren't same.

def list_convert(document):

   return list(key_find(document))


def key_find(document):

  if isinstance(document, dict):
    for k, v in iteritems(document):
        if k == 'a_table':
             yield v
        elif k == 'b_table':
            yield v

        if isinstance(v, dict):
            for result in key_find(v):
                yield result
        elif isinstance(v, list):
            for d in v:
                for result in key_find(d):
                    yield result

How can I achieve this ?

So I have added 4 configs and they all have occurence of a_table and b_table.

Present output I'm getting is

Present O/P -('t0', 't1', 't2', 't3', 't5', 't6', 't9', 't10')
Expected O/P - ('t0', 't1'),('t2', 't3'),('t5', 't6'),('t9', 't10')

Related Questions