Last active
September 17, 2020 08:26
-
-
Save grzes/73142ed99dc8ad6ac4fc9fb9f4e87d60 to your computer and use it in GitHub Desktop.
Django's legacy DotExpendedDict
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
class DotExpandedDict(dict): | |
""" | |
A special dictionary constructor that takes a dictionary in which the keys | |
may contain dots to specify inner dictionaries. It's confusing, but this | |
example should make sense. | |
>>> d = DotExpandedDict({'person.1.firstname': ['Simon'], \ | |
'person.1.lastname': ['Willison'], \ | |
'person.2.firstname': ['Adrian'], \ | |
'person.2.lastname': ['Holovaty']}) | |
>>> d | |
{'person': {'1': {'lastname': ['Willison'], 'firstname': ['Simon']}, '2': {'lastname': ['Holovaty'], 'firstname': ['Adrian']}}} | |
>>> d['person'] | |
{'1': {'lastname': ['Willison'], 'firstname': ['Simon']}, '2': {'lastname': ['Holovaty'], 'firstname': ['Adrian']}} | |
>>> d['person']['1'] | |
{'lastname': ['Willison'], 'firstname': ['Simon']} | |
# Gotcha: Results are unpredictable if the dots are "uneven": | |
>>> DotExpandedDict({'c.1': 2, 'c.2': 3, 'c': 1}) | |
{'c': 1} | |
""" | |
def __init__(self, key_to_list_mapping): | |
for k, v in key_to_list_mapping.items(): | |
current = self | |
bits = k.split('.') | |
for bit in bits[:-1]: | |
current = current.setdefault(bit, {}) | |
# Now assign value to current position | |
try: | |
current[bits[-1]] = v | |
except TypeError: # Special-case if current isn't a dict. | |
current = {bits[-1]: v} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment