Skip to content

Instantly share code, notes, and snippets.

@prologic
Last active August 29, 2015 14:19
Show Gist options
  • Save prologic/9b31c053d1be2ebab8bd to your computer and use it in GitHub Desktop.
Save prologic/9b31c053d1be2ebab8bd to your computer and use it in GitHub Desktop.
Playing with Stackoverflow Question: 29762824
key1:
nested-key1 = val1
nested-key2 = val2
key2:
nested-key3 = val3
#!/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)
#!/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)
#!/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)
@prologic
Copy link
Author

Trying to answer Stackoverflow Quesiton: 29762824

Transition from naive solution based on what you would normally do to a purely functional approach using the Funcy library.

  • test.py -- traditions/naive approach
  • test2.py -- using list comphrensions
    -- test3.py -- pure functional approach with list comprehensions and funcy

@prologic
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment