Skip to content

Instantly share code, notes, and snippets.

@sma
Created December 20, 2009 20:40
Show Gist options
  • Save sma/260626 to your computer and use it in GitHub Desktop.
Save sma/260626 to your computer and use it in GitHub Desktop.
parse a simple key-value data structure
example = """
start
{
position1 "-1022.963745,793.409607,8.966581"
position2 "-1024.971558,70.542549,416.005066"
name "Start"
time 0.0
active 1
give
{
item "flashlight"
weapon "rpg"
ammo
{
amount 20
type "rocket"
}
}
}
"""
def parse(itr):
kv = {}
for line in itr:
line = line.strip()
if " " in line:
key, value = line.split(" ", 1)
value = value.strip()
if value[0] == '"' and value[-1] == '"': kv[key] = value[1:-1]
else: kv[key] = float(value) if "." in value else int(value)
elif line == "{":
kv[name] = parse(itr)
elif line == "}":
break
elif line:
name = line
return kv
print parse(iter(example.splitlines()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment