DEV Community

Discussion on: Use dot syntax to access dictionary key - Python Tips

Collapse
michrodz profile image
Mich Rodz

How would implement: foo["bar"]["baz"] to be equal to foo.bar.baz?

Collapse
0xbf profile image
Bo Author

You can try this, change the __getattr__ to:

def __getattr__(self, key):
    try:
        return self[key]
    except KeyError as k:
        self[key] = value = DictX()
        return value
Enter fullscreen mode Exit fullscreen mode

Then use it:

data = DictX()
data.person.firstname = "bo"
print(data.person.firstname)
print(data["person"]["firstname"])
print(data)
Enter fullscreen mode Exit fullscreen mode

Result:

bo
bo
<DictX {'person': <DictX {'firstname': 'bo'}>}>
Enter fullscreen mode Exit fullscreen mode