CONFIG.SYS
  • ALL_POSTS.BAT
  • ABOUT.EXE

Access a dictionary using path style - Wed, Apr 6, 2022

Access a dictionary using path style

Recently I was programming some CI code in python for getting some information from yaml files. These yaml files were loaded using the yaml.load function that returns a dict.
In order to access the values needed, I used code like this:

pod_name = pod_spec['metadata']['name']

Since this syntax can get quiet lengthy I thought that using a path syntax like metadata.name would be more readable:

pod_name = pod_spec('metadata.name')

Well, this syntax wouldn’t work that easy, so I wrote a smaller helper function based on this nice code :

def find(element, dictionary):
    keys = element.split('.')
    rv = dictionary
    for key in keys:
        if re.search('\\[\\d+\\]', key):
            key = int(re.search('\\d+', key).group())
        rv = rv[key]
    return rv

This function lets me right code like the following, accessing the values in a path style:

source_ref_name = find("spec.chart.spec.sourceRef.name", self.yaml_doc)

The code is a little bit more complicated than the initial code because of the introduction of the method. But I think this is outweighed by the nice way I can not use paths.
The complete code with an example can be found here .

Back to Home


21st century version | © Thomas Reuhl 2025 | Disclaimer | Built on Hugo

Linkedin GitHub