Last active
February 27, 2018 21:36
-
-
Save TomFaulkner/329c53cba28a52f5e32410411f31e36c to your computer and use it in GitHub Desktop.
Instant nested dicts
This file contains 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
# 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