Sitemap

Access Python Dictionary Information Using Dot Notation

2 min readDec 30, 2022

--

In Python, we can define a dictionary as follows:

dictionary = {'a': 1, 'b': 2}

To retrieve the values corresponding to the keys ‘a’ and ‘b’, we can use the following syntax:

dictionary['a']
dictionary['b']

While this method works well for small dictionaries, it can become tedious when retrieving values repeatedly. An alternative is to use dot notation, as shown below:

dictionary.a
dictionary.b

Unfortunately, Python does not support dot notation for dictionaries by default. There are workarounds such as data classes, but a quick and easy solution is to use functions.

Get Pythagoras’s stories in your inbox

Join Medium for free to get updates from this writer.

To make a dictionary dot-accessible, we can use the following function:

def dot_function(kwargs):
dot_function.__dict__.update(**kwargs)
return dot_function

To transform a dictionary into a dot-accessible form, we can use the following code:

dot_dictionary = dot_function(dictionary)

Then, we can access the values corresponding to the keys as follows:

dot_dictionary.a
dot_dictionary.b

This function uses closures, which are function objects that have memory. We can determine whether a function is a closure by checking whether it returns its own name. In this example, the function name is dot_function and it returns dot_function. Closures have memory in the sense that even after executing the function, its parameters remain in memory and can be accessed again.

Functions in Python are instances of a class, and the attributes of a class are stored in a dictionary that can be accessed using class_instance.__dict__. For our function, the class instance is dot_function, so the dictionary that stores its attributes is dot_function.__dict__.

We update the empty dot_function.__dict__ dictionary with our own key-value pairs using the update method of the dictionary class. This step also makes the keys of our dictionary attributes of the dot_function class instance. These keys can then be accessed using the dot notation, just like any other class attributes.

I hope this technique proves useful in your projects.

--

--

Pythagoras
Pythagoras

Written by Pythagoras

0 followers

Always curious.