Skip to content

Instantly share code, notes, and snippets.

@Billcountry
Last active April 6, 2020 04:09
Show Gist options
  • Save Billcountry/c5aec062c52bb09a29ff5c6e9096d743 to your computer and use it in GitHub Desktop.
Save Billcountry/c5aec062c52bb09a29ff5c6e9096d743 to your computer and use it in GitHub Desktop.
An improvement over built in dictionary allowing you to access values using a `dot` notation.
import json
class Dict(dict):
def __init__(self, **kwargs):
super(Dict, self).__init__()
for key, value in kwargs.items():
self[key] = value # Takes advantage of __setitem__ logic
def __json__(self):
return json.dumps(self)
def __getattr__(self, name):
"""Allow dictionary access with a 'dot' notation. e.g. user.name"""
return self.get(name)
def __setattr__(self, key, value):
"""Set dictionary values with a 'dot' notation. e.g. user.name='Jane Doe'"""
return self.__setitem__(key, value)
def __setitem__(self, key, value):
if isinstance(value, dict) and not isinstance(value, Dict):
value = Dict(**value)
super(Dict, self).__setitem__(key, value)
@Billcountry
Copy link
Author

Example:

user = Dict(first_name="Jane", last_name="Doe", age=20)
print(user.get("first_name")  # Jane
print(user.first_name)  # Jane
print(user["first_name]) # Jane

print(user.next_of_kin)  # None
user.next_of_kin = {"first_name": "John", "last_name": "Doe"}

print(user.next_of_kin)  # {"first_name": "John", "last_name": "Doe"}
print(user.next_of_kin.first_name)  # John

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment