Skip to content

Instantly share code, notes, and snippets.

@tom1299
Last active April 6, 2022 10:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tom1299/c53c6cc714eee08d0f0e21a87b8f06c4 to your computer and use it in GitHub Desktop.
Save tom1299/c53c6cc714eee08d0f0e21a87b8f06c4 to your computer and use it in GitHub Desktop.
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