Skip to content

Instantly share code, notes, and snippets.

Last active Apr 6, 2022
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'\\[\\d+\\]', key):
key = int('\\d+', key).group())
rv = rv[key]
return rv
if __name__ == '__main__':
# Example from here:
example_yaml = """
doe: "a deer, a female deer"
ray: "a drop of golden sun"
pi: 3.14159
xmas: true
french-hens: 3
- huey
- dewey
- louie
- fred
calling-birds: four
french-hens: 3
golden-rings: 5
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"
Copy link

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