Created
July 22, 2021 21:36
-
-
Save mpharrigan/1bffc0a146715a47f62dc5b367fd4c1e to your computer and use it in GitHub Desktop.
flatten dataclass
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
def _flat_dict(flat_record, record, prefix): | |
for k, v in record.items(): | |
if isinstance(v, dict): | |
_flat_dict(flat_record, record[k], prefix+(k,)) | |
else: | |
flat_record[prefix+(k,)] = v | |
def flatten(dd): | |
fd = {} | |
_flat_dict(fd, dd, tuple()) | |
return fd | |
from collections import defaultdict | |
def abbrev(fullyqual, joiner='_'): | |
# First, assume we only need the last element | |
num_levels = {fullkey: 1 for fullkey in fullyqual.keys()} | |
while True: | |
rev_mapping = defaultdict(list) | |
for fullkey in fullyqual.keys(): | |
trunckey = fullkey[-num_levels[fullkey]:] | |
rev_mapping[trunckey].append(fullkey) | |
all_unambig = True | |
for trunckey, fullkeys in rev_mapping.items(): | |
if len(fullkeys) > 1: | |
for fk in fullkeys: | |
num_levels[fk] += 1 | |
all_unambig = False | |
if all_unambig: | |
break | |
abbreved = {} | |
for trunckey, fullkeys in rev_mapping.items(): | |
fullkey, = fullkeys # only one | |
if joiner is not None: | |
trunckey = '_'.join(trunckey) | |
abbreved[trunckey] = fullyqual[fullkey] | |
return abbreved | |
nesty = { | |
'building': {'width': 10, 'height': 400}, | |
'person': {'width': 1, 'height': 2}, | |
'other_thing': 25, | |
'final_thing_container': {'final_thing': 5}, | |
} | |
flatten(nesty) | |
abbrev(flatten(nesty)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment