DEV Community

BC
BC

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

Top comments (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
 
zbigniew_rajewski_09546ca profile image
Zbigniew Rajewski • Edited

It is always good to use builtins like SimpleNamespace. But if you really need something advanced to crawl through structures by dot notation then you should try Jsify library (citsystems.github.io/jsify/)

Collapse
 
anrodriguez profile image
An Rodriguez

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

Collapse
 
bitecode profile image
BC

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