Python - Parse YAML dict to get keys by heirarchy

Doc

I have a YAML dict in which I need to iterate over the 2nd keys of the heirarchy (/home,/career,/help,/) to find the existance of the key "pass_key". The location for the "pass_key" will always be fixed (4th heirarchy).

api:
  /home:
    post:
      pass_key: some_value
  /career:
    get:
      pass_key: some_value
  /help:
    post:
      pass_key: some_value

The challenge is, I am unable to get the key without knowing the name of it as putting asterisk doesn't help here :) How can I achieve this? Any help would appreciated. Thanks!

import yaml

with open(r'./test.yaml') as file:
    api = yaml.load(file, Loader=yaml.FullLoader)
    check_key = api['api'][*][*]['pass_key']
    print(check_key)

error line 5 paths = api['api'][][]['pass_key'] ^ SyntaxError: invalid syntax

drompix

If you're 100% sure about the dictionary structure, as a trivial solution it is possible to use basic loops:

for layer2_vals in api['api'].values():
    for layer3_vals in layer2_vals.values():
        print(layer3_vals['pass_key'])

output is

some_value
some_value
some_value

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related