Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for YAML. More Types by colinmcnicholl
# Taken from mission YAML. Simple Dict
from itertools import chain, zip_longest
import re
switch = {
'false': lambda: False,
'true': lambda: True,
'null': lambda: None,
'"null"': lambda: 'null'
}
def default_case(value):
raise Exception('No case found!')
def run_switch(value):
return switch.get(value, default_case)()
def flatten(listOfLists):
return chain.from_iterable(listOfLists)
def yaml(a):
parts = a.split(':')
for i, part in enumerate(parts):
el_part = part.split('\n')
parts[i] = el_part
flat_parts = [el for el in flatten(parts) if el]
keys = flat_parts[::2]
keys = [el.strip('"') if el.startswith('"') and el.endswith('"')
else el for el in keys]
values = [int(el) if el.strip().isdigit() else el.strip(' ')
for el in flat_parts[1::2]]
values = [el.strip('"') if isinstance(el, str) and el.startswith('"')
and el.endswith('"') and el[-2] != '"' and el != '"null"'
else el for el in values]
new_values = []
for el in values:
if el in switch:
el = run_switch(el)
new_values.append(el)
else:
new_values.append(el)
p = re.compile(r'\\')
for i, el in enumerate(new_values[:]):
if isinstance(el, str):
s = p.search(el)
if s:
new_values[i] = el.replace(el[s.start():s.end()], "")[1:-1]
else:
continue
return dict(zip_longest(keys, new_values, fillvalue=None))
if __name__ == '__main__':
print("Example:")
print(yaml('name: Alex\nage: 12'))
# These "asserts" are used for self-checking and not for an auto-testing
assert yaml('name: Alex\nage: 12') == {'age': 12, 'name': 'Alex'}
assert yaml('name: Alex Fox\n'
'age: 12\n'
'\n'
'class: 12b') == {'age': 12,
'class': '12b',
'name': 'Alex Fox'}
assert yaml('name: "Alex Fox"\n'
'age: 12\n'
'\n'
'class: 12b') == {'age': 12,
'class': '12b',
'name': 'Alex Fox'}
assert yaml('name: "Alex \\"Fox\\""\n'
'age: 12\n'
'\n'
'class: 12b') == {'age': 12,
'class': '12b',
'name': 'Alex "Fox"'}
assert yaml('name: "Bob Dylan"\n'
'children: 6\n'
'alive: false') == {'alive': False,
'children': 6,
'name': 'Bob Dylan'}
assert yaml('name: "Bob Dylan"\n'
'children: 6\n'
'coding:') == {'children': 6,
'coding': None,
'name': 'Bob Dylan'}
assert yaml('name: "Bob Dylan"\n'
'children: 6\n'
'coding: null') == {'children': 6,
'coding': None,
'name': 'Bob Dylan'}
assert yaml('name: "Bob Dylan"\n'
'children: 6\n'
'coding: "null" ') == {'children': 6,
'coding': 'null',
'name': 'Bob Dylan'}
print("Coding complete? Click 'Check' to earn cool rewards!")
Nov. 13, 2019
Comments: