Last active
November 12, 2019 17:07
-
-
Save RNHTTR/20b27491a3f0602006cdea0adb635218 to your computer and use it in GitHub Desktop.
Simple recursive function to convert a yaml literal block string ("|-") to yaml-valid python dictionary
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
def dictionarize(s, d={}, key=None): | |
""" | |
Simple recursive function to convert a yaml literal block string ("|-") to yaml-valid python dictionary | |
Args: | |
s, str: yaml-valid input string | |
d, dict: output dictionary | |
key, str: key in the dictionary at which to add nested values | |
Returns: | |
d, dict: yaml-valid python dictionary | |
""" | |
if isinstance(s, str): | |
s = s.split('\n') | |
for kv in list(s): | |
try: | |
k, v = kv.split(':') | |
except ValueError: | |
if kv in s: | |
s.remove(kv) | |
dictionarize(s, d) | |
if v: | |
if key: | |
d[key][k.strip()] = v.strip() | |
else: | |
d[k] = v.strip() | |
else: | |
key = k.strip() | |
d[k.strip()] = {} | |
if kv in s: | |
s.remove(kv) | |
return d |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment