Skip to content

Instantly share code, notes, and snippets.

@aragaer
Created July 2, 2019 08:34
Show Gist options
  • Save aragaer/3e6c015cc702cf7198bed4f1e54e462a to your computer and use it in GitHub Desktop.
Save aragaer/3e6c015cc702cf7198bed4f1e54e462a to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
def make_container_for(key):
if isinstance(key, int):
return [None] * (key+1)
else:
return {}
def build(val, path):
for key in reversed(path):
cont = make_container_for(key)
cont[key] = val
val = cont
return val
def add(val, path, root=None):
if root is None:
result = make_container_for(path[0])
else:
result = root
root = result
for i, key in enumerate(path[:-1]):
try:
root = root[key]
except KeyError:
root[key] = build(val, path[i+1:])
return result
except IndexError:
root.extend([None]*(key-len(root)))
root = root[key]
try:
key = path[-1]
root[key] = val
except IndexError:
root.extend([None]*(key-len(root)+1))
root[key] = val
return result
if __name__ == '__main__':
r = add("hello", ('a',))
r = add("hello", ('b',1,), r)
r = add("hello", ('b',2,), r)
print(r)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment