Last active
August 29, 2015 14:19
-
-
Save prologic/9b31c053d1be2ebab8bd to your computer and use it in GitHub Desktop.
Playing with Stackoverflow Question: 29762824
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
key1: | |
nested-key1 = val1 | |
nested-key2 = val2 | |
key2: | |
nested-key3 = val3 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from pprint import pprint | |
data = {} | |
with open("test.conf", "r") as f: | |
for line in f: | |
line = line.strip() | |
if line.endswith(":"): | |
key = line.rstrip(":") | |
data[key] = {} | |
elif "=" in line: | |
k, v = map(str.strip, line.split("=", 1)) | |
data[key][k] = v | |
pprint(data) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from pprint import pprint | |
data = {} | |
lines = map(str.strip, open("test.conf", "r").readlines()) | |
for line in lines: | |
if line.endswith(":"): | |
key = line.rstrip(":") | |
data[key] = {} | |
elif "=" in line: | |
k, v = map(str.strip, line.split("=", 1)) | |
data[key][k] = v | |
pprint(data) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from funcy import * # noqa | |
from pprint import pprint | |
lines = open("test.conf", "r").readlines() | |
xs = map(str.strip, lines) # strip surrounding whitespace | |
xs = filter(None, xs) # strip blank lines | |
ys = partition_by(rpartial(str.endswith, ":"), xs) # partition by : (denoting a key) | |
zs = chunks(2, ys) # chunks of 2 [[key, values], [key, values]] | |
data = dict((x[0].rstrip(":"), dict(chunks(2, map(str.strip, mapcat(rpartial(str.split, "="), y))))) for x, y in zs) | |
pprint(data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think the last line in
test3.py
(data = ...
) could be vastly improved. Also I think a lot of this could simply be done with itertools and list/dict comprehensions and a few functions.