Last active
April 6, 2022 10:02
-
-
Save tom1299/c53c6cc714eee08d0f0e21a87b8f06c4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.