DEV Community

Bo
Bo

Posted on

Use dot syntax to access dictionary key - Python Tips

We can create our own class to use the dot syntax to access a dictionary's keys.

class DictX(dict):
    def __getattr__(self, key):
        try:
            return self[key]
        except KeyError as k:
            raise AttributeError(k)

    def __setattr__(self, key, value):
        self[key] = value

    def __delattr__(self, key):
        try:
            del self[key]
        except KeyError as k:
            raise AttributeError(k)

    def __repr__(self):
        return '<DictX ' + dict.__repr__(self) + '>'

Enter fullscreen mode Exit fullscreen mode

Our class DictX here inherit Python's builtin dict.

Now use it we just need to wrap a native dictionary with this DictX class:

data = DictX({
    "name": "bo"
})

# use dot to get
print(data.name)
print(data["name"])

# use dot to set
data.state = "NY"
print(data.state)
print(data["state"])

# use dot to delete
del data.state
print(data)
Enter fullscreen mode Exit fullscreen mode

Printed result:

bo
bo
NY
NY
<DictX {'name': 'bo'}>
Enter fullscreen mode Exit fullscreen mode

Discussion (4)

Collapse
waylonwalker profile image
Waylon Walker

This is such a fun example of how easy it is to be creative and make your own implementation of anything in python.

I often use simple namespaces or data classes to get this effect with vanilla types.

Collapse
yujiri8 profile image
Ryan Westlund

Wow, I tried to implement this a while back and failed because I didn't know __getattr__ was a thing and tried to use __getattribute__! Thanks for this.

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