Skip to content

Instantly share code, notes, and snippets.

@TomFaulkner
Last active February 27, 2018 21:36
Show Gist options
  • Save TomFaulkner/329c53cba28a52f5e32410411f31e36c to your computer and use it in GitHub Desktop.
Save TomFaulkner/329c53cba28a52f5e32410411f31e36c to your computer and use it in GitHub Desktop.
Instant nested dicts
# Borrowed from:
# https://stackoverflow.com/questions/2600790/multiple-levels-of-collection-defaultdict-in-python
class AutoVivification(dict):
"""Implementation of perl's autovivification feature."""
def __getitem__(self, item):
try:
return dict.__getitem__(self, item)
except KeyError:
value = self[item] = type(self)()
return value
data = [('a', 'b', 'c', 'd', 1), ('e', 'f', 'g', 'h', 2)]
results = AutoVivification()
for uuid, view, cat, subcat, value in data:
results[view][cat]['subcategories'][subcat]['uuid'] = uuid
results[view][cat]['subcategories'][subcat]['value'] = value
print(results)
'b': {'c': {'subcategories': {'d': {'uuid': 'a', 'value': 1}}}}, 'f': {'g': {'subcategories': {'h': {'uuid': 'e', 'value': 2}}}}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment