29 lines
1015 B
Python
29 lines
1015 B
Python
|
G
|
def parse_kv(text):
|
||
|
|
"""Parse a multiline string of 'key=value' lines into a dict.
|
||
|
|
Blank lines are ignored. Values that consist solely of digits are
|
||
|
|
converted to int.
|
||
|
|
"""
|
||
|
|
result = {}
|
||
|
|
for line in text.splitlines():
|
||
|
|
line = line.strip()
|
||
|
|
if not line:
|
||
|
|
continue
|
||
|
|
# Expect key=value format; split on first '='
|
||
|
|
if '=' not in line:
|
||
|
|
# If line does not contain '=', skip it (or raise error).
|
||
|
|
# According to spec we assume valid lines.
|
||
|
|
continue
|
||
|
|
key, value = line.split('=', 1)
|
||
|
|
# Convert to int if the value is all digits
|
||
|
|
if value.isdigit():
|
||
|
|
value = int(value)
|
||
|
|
result[key] = value
|
||
|
|
return result
|
||
|
|
|
||
|
|
if __name__ == "__main__":
|
||
|
|
# Test case from the task description
|
||
|
|
test_input = "a=1\nb=hello\n\nc=42"
|
||
|
|
expected = {'a': 1, 'b': 'hello', 'c': 42}
|
||
|
|
result = parse_kv(test_input)
|
||
|
|
assert result == expected, f"Expected {expected}, got {result}"
|
||
|
|
print("Test passed")
|