Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Uncategorized category for YAML. Complex Structure by Iyanah.K
def yaml(a: str):
import re
# Remove empty lines and full-line comments
lines = [line.rstrip() for line in a.splitlines() if line.strip() and not line.strip().startswith("#")]
# Remove inline comments (outside quotes)
def strip_inline_comment(s):
result = ""
in_single = in_double = False
i = 0
while i < len(s):
ch = s[i]
if ch == '"' and not in_single:
in_double = not in_double
elif ch == "'" and not in_double:
in_single = not in_single
elif ch == "#" and not in_single and not in_double:
break # stop at unquoted #
result += ch
i += 1
return result.rstrip()
# Convert string values into Python types
def convert_value(val):
val = val.strip()
if val == "" or val.lower() == "null":
return None
elif val.lower() == "false":
return False
elif val.lower() == "true":
return True
elif val.isdigit():
return int(val)
elif (val.startswith('"') and val.endswith('"')) or (val.startswith("'") and val.endswith("'")):
return val[1:-1].replace('\\"', '"')
return val
# Parse YAML lists
def parse_list(start=0, indent=0):
result = []
i = start
while i < len(lines):
line = lines[i]
stripped = line.lstrip()
current_indent = len(line) - len(stripped)
if current_indent < indent:
break
if stripped.startswith("-"):
value = strip_inline_comment(stripped[1:].strip())
nested_indent = current_indent + 2
# Collect nested lines
nested_start = i + 1
nested_lines = []
while nested_start < len(lines):
next_line = lines[nested_start]
next_indent = len(next_line) - len(next_line.lstrip())
if next_indent < nested_indent:
break
nested_lines.append(lines[nested_start])
nested_start += 1
nested_value = None
if nested_lines:
first_stripped = nested_lines[0].lstrip()
if first_stripped.startswith("-"):
nested_value, _ = parse_list(i + 1, nested_indent)
else:
nested_value, _ = parse_dict(i + 1, nested_indent)
i = nested_start - 1
if value:
value = convert_value(value)
if nested_value is not None:
if isinstance(nested_value, list):
value = [value] + nested_value
else:
value = [value, nested_value]
else:
value = nested_value if nested_value is not None else None
result.append(value)
i += 1
return result, i
# Parse YAML dicts
def parse_dict(start=0, indent=0):
result = {}
i = start
while i < len(lines):
line = lines[i]
stripped = line.lstrip()
current_indent = len(line) - len(stripped)
if current_indent < indent:
break
if ":" in stripped:
key, val = stripped.split(":", 1)
key = key.strip()
val = strip_inline_comment(val.strip())
nested_indent = current_indent + 2
# Collect nested lines
j = i + 1
nested_lines = []
while j < len(lines):
next_line = lines[j]
next_indent = len(next_line) - len(next_line.lstrip())
if next_indent < nested_indent:
break
nested_lines.append(lines[j])
j += 1
if nested_lines:
first_stripped = nested_lines[0].lstrip()
if first_stripped.startswith("-"):
nested_value, _ = parse_list(i + 1, nested_indent)
else:
nested_value, _ = parse_dict(i + 1, nested_indent)
val = nested_value
i = j - 1
elif val == "":
val = None
else:
val = convert_value(val)
result[key] = val
i += 1
return result, i
# Root: list or dict
if lines and lines[0].lstrip().startswith("-"):
parsed, _ = parse_list()
else:
parsed, _ = parse_dict()
return parsed
# ✅ Tests
assert yaml('- Alex\n-\n - odessa\n - dnipro\n- Li') == ['Alex', ['odessa', 'dnipro'], 'Li']
assert yaml('# comment\n- write some # after\n# one mor\n- "Alex Chii #sir "\n- 89 #bl') == ['write some', 'Alex Chii #sir ', 89]
print("✅ All tests passed!")
Oct. 29, 2025
Comments: