Based on the StackOverflow answer
Last active
August 28, 2021 03:17
-
-
Save blacksmithop/9b23675d5355bde9282a0e3e98c22b51 to your computer and use it in GitHub Desktop.
Python dict, dot notation support
This file contains hidden or 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 Map(dict): | |
""" | |
Example: | |
m = Map({'first_name': 'Eduardo'}, last_name='Pool', age=24, sports=['Soccer']) | |
""" | |
def __init__(self, *args, **kwargs): | |
self.update(*args,**kwargs) | |
if kwargs: | |
for k, v in kwargs.items(): | |
self[k] = v | |
def __getattr__(self, attr): | |
return self.get(attr) | |
def __setattr__(self, key, value): | |
self.__setitem__(key, value) | |
def __setitem__(self, key, value): | |
super(Map, self).__setitem__(key, value) | |
self.__dict__.update({key: value}) | |
def __missing__(self,key): | |
value=self[key]= type(self)() | |
return value | |
def __delattr__(self, item): | |
self.__delitem__(item) | |
def __delitem__(self, key): | |
super(Map, self).__delitem__(key) | |
del self.__dict__[key] | |
m = Map({'first_name': 'Eduardo'}, last_name='Pool', age=24, sports=['Soccer']) | |
# Add new key | |
m.new_key = 'Hello world!' | |
# Or | |
m['new_key'] = 'Hello world!' | |
print(m.new_key) | |
# Missing key returns empty dict | |
print(m['abc']) | |
# Update values | |
m.new_key = 'Yay!' | |
# Or | |
m['new_key'] = 'Yay!' | |
# Delete key | |
del m.new_key # Or del m['new_key'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment