Skip to content

Instantly share code, notes, and snippets.

@RNHTTR
Last active November 12, 2019 17:07
Show Gist options
  • Save RNHTTR/20b27491a3f0602006cdea0adb635218 to your computer and use it in GitHub Desktop.
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
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