Created
January 29, 2017 10:06
-
-
Save uda/b3707e45b789e8957806fb7bb6ae6547 to your computer and use it in GitHub Desktop.
BubbleDict
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
""" | |
License: MIT https://uda.mit-license.org/ | |
Author: Yehuda Deutsch <yeh@uda.co.il> | |
BubbleDict is a stupid to need class, but given some data structures, this might come handy. | |
When you need to populate a dict recursively, and some levels might not be set yet, this is to avoid multiple ifs in the code. | |
Before: | |
``` | |
multi_level_dict = {} | |
for item in item_list.items(): | |
if not item.key in multi_level_dict: | |
multi_level_dict[item.key] = {} | |
if not item.cat in multi_level_dict[item.key]: | |
multi_level_dict[item.key][item.cat] = {} | |
multi_level_dict[item.key][item.cat][item.type] = item.name | |
``` | |
After: | |
``` | |
multi_level_dict = {} | |
for item in item_list.items(): | |
multi_level_dict.a(item.key).a(item.cat)[item.type] = item.name | |
``` | |
Notes: | |
Remember to pass `dict(bubbled_dict)` if you need a dict instance, some libraries will error if not. | |
I tried manipulating `__getitem__`, but that turned to be an issue when using an instance within template engines. | |
If you have any ideas, please let me know, here in the gist or by email. | |
""" | |
class BubbleDict(dict): | |
def bubble(self, name): | |
""" | |
:param str name: | |
:rtype: BubbleDict | |
""" | |
if name not in self: | |
self[name] = self.__class__() | |
return self[name] | |
b = bubble |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment