Skip to content

Instantly share code, notes, and snippets.

@tom1299
Last active Apr 6, 2022
Embed
What would you like to do?
import re
import yaml
def find(element, dictionary):
"""
Find a value given a path like a.b.c
"""
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
if __name__ == '__main__':
# Example from here: https://www.cloudbees.com/blog/yaml-tutorial-everything-you-need-get-started
example_yaml = """
doe: "a deer, a female deer"
ray: "a drop of golden sun"
pi: 3.14159
xmas: true
french-hens: 3
calling-birds:
- huey
- dewey
- louie
- fred
xmas-fifth-day:
calling-birds: four
french-hens: 3
golden-rings: 5
partridges:
count: 1
location: "a pear tree"
turtle-doves: two
"""
example = yaml.load(example_yaml, Loader=yaml.FullLoader)
assert find("xmas-fifth-day.partridges.count", example) == 1
assert find("calling-birds.[0]", example) == "huey"
@tom1299
Copy link
Author

tom1299 commented Apr 6, 2022

The method find lets you access values in a dict using a path notation. Note that there are a few cases where this might fail. For example when using [ in keys.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment