26 lines
804 B
Python
26 lines
804 B
Python
|
G
|
def parse_kv(text: str) -> dict:
|
||
|
|
"""Parse lines of the form 'key=value' into a dict.
|
||
|
|
Blank lines are ignored. Values that consist only of digits are converted to int.
|
||
|
|
"""
|
||
|
|
result = {}
|
||
|
|
for line in text.splitlines():
|
||
|
|
line = line.strip()
|
||
|
|
if not line:
|
||
|
|
continue
|
||
|
|
if '=' not in line:
|
||
|
|
continue
|
||
|
|
key, value = line.split('=', 1)
|
||
|
|
key = key.strip()
|
||
|
|
value = value.strip()
|
||
|
|
if value.isdigit():
|
||
|
|
value = int(value)
|
||
|
|
result[key] = value
|
||
|
|
return result
|
||
|
|
|
||
|
|
if __name__ == "__main__":
|
||
|
|
# Test case
|
||
|
|
test_input = "a=1\nb=hello\n\nc=42"
|
||
|
|
expected = {'a': 1, 'b': 'hello', 'c': 42}
|
||
|
|
assert parse_kv(test_input) == expected, f"Test failed: got {parse_kv(test_input)}"
|
||
|
|
print("All tests passed.")
|