As long as we use Python, the dictionary is a data structure that we almost can’t avoid using. I would say that the Python dictionary is already good enough in terms of flexibility. After all, the Python language itself is famous for being dynamic.
However, if you also use JavaScript for some purposes as I do, you may be familiar with using "dot" to get object values from a dictionary. This article will start with an example to show what is the inconvenience that Munch tries to solve. Then, I’ll introduce the other features that this library has.
Original Python Dictionary

I presume that most developers like you are already familiar with Python dictionaries. Here is a sample dictionary that is created for demo purpose.
my_profile = {
'name': 'Chris',
'age': 33,
'address': {
'country': 'Australia',
'state': 'Victoria'
}
}
If we want to get the value of "name", just do my_profile['name']
.

If we want to get the value of "country, we can chain the square bracket because it is nested inside the object "address".

Honestly, there is no serious problem. If we insist to find one, it is that the key has to be a string. Unless we define a proper class and instantiate my_profile
as an instance, we have to use string to get the values.
Munch is such a library to bypass this issue.
Use Munch Dictionary

Munch is registered in PyPI, so we can easily get it using pip.
pip install munch
Once we have got the library, the class Munch
needs to be imported from the module.
from munch import Munch
Then, we can define our dictionary as follows.
my_profile = Munch({
'name': 'Chris',
'age': 33,
'address': Munch({
'country': 'Australia',
'state': 'Victoria'
})
})
Then, the major difference between a Munch dictionary and a Python dictionary is that the former supports "dot" syntax to get the values.

In the above example, we don’t have to use strings to get the value. The benefit is that it is more reliable and convenient because most of the IDE tools will have auto-completion of the keys.

If you’re not sure why using an accessible attribute is more reliable than a string, please refer to one of my previous articles.
How To Make Fewer "Mistakes" In Python
Building Munch Dictionary

You may have noticed that in the previous example we created the Munch dictionary from a Python dictionary. Of course, this is convenient if we have got a dictionary existing, and we just want to use some features from Munch.
However, sometimes we may want to build a dictionary when it is not existing. In this case, we DO NOT have to firstly build a Python dictionary and then convert it to Munch. We can use the dot syntax to build the dictionary from the beginning. This is very similar to JavaScript.
For example, we want to re-build the dictionary that we have used in the previous example.
my_new_profile = Munch()
This can be treated as my_new_profile = {}
, but we have Munch features from the beginning. So we can do the following to append the key-value pairs.
my_new_profile.name = 'Chris'
my_new_profile.age = 33
my_new_profile.address = Munch()
my_new_profile.address.country = "Australia"
my_new_profile.address.state = "Victoria"
The my_new_profile
will be the same as my_profile
.

Munch is Yet a Subclass of Dictionary

In fact, the Munch class is a subclass of the Python dictionary.

The example above shows that my_new_profile
we have created is both Munch and dict
. By knowing this, it is confident to say that Munch will also inherit all the original features from Python Dictionary.
For example, we can still use a string to set a key-value pair or get a value. We may still need this feature if the key is a variable.
my_new_profile['programming_language'] = 'Python'
my_new_profile['programming_language']

Of course, all the functions of the Python dictionary will also be available here, such as getting all the keys of a Munch dictionary.
my_new_profile.keys()

Serialisation is one of the most important features of a Python dictionary. Very frequently, we may want to convert between a Python dictionary and a JSON string. Apparently, by using Munch, we never lose this feature.
# Serialisation
import json
profile_json = json.dumps(my_new_profile)
print(profile_json)

Default Values

Now, let’s have a look what are the other cool features that Munch provides. The default value is one of them.
One of the important tips we need to know about Python Dictionary is the Key Error.

It is recommended to use the get()
function when there is a concern about the key error. We can set the default value when using this function.
my_profile.get('programming_language', 'undefied')

This is not bad, but we have to pass in the default values every time we use the get()
function. With the Munch dictionary, we only need to do it ONCE.
from munch import DefaultMunch
my_profile = DefaultMunch('undefined', {
'name': 'Chris',
'age': 33
})
As shown, this time we need to import the DefaultMunch
class. When we define the dictionary, the first object will be the default value when we try to get a key that does not exist. Let’s give it a try.
my_profile.whatever_not_exists

When the key does not exist, the pre-defined default value will be returned. If it does exist, the value is returned properly.
Add Keys Upon Query

Another little sugar block of the Munch library is the Default Factory class. When we try to get a value from a key, the key will be automatically added to the Munch dictionary if it does not exist.
We need to define a Munch dictionary with the DefaultFactoryMunch
class.
from munch import DefaultFactoryMunch
my_profile = DefaultFactoryMunch(list, {
'name': 'Chris',
'age': 33
})
Please be noticed that the default value need to be defined in an instance of the DefaultFactoryMunch
. This default value will be used when a non-existing key is accessed.
Suppose we are querying the Munch dictionary. We want to add value to the key if the key returns nothing.
if not my_profile.languages:
my_profile.languages.append('Python')
print(my_profile.languages)

It guaranteed that my profile has to have Python 🙂
Summary

In this article, I have introduced the library called Munch. It fully inherits the Python dictionary so that it supports all the original features we are familiar with. Additionally, it supports "dot syntax". This is more convenient and reliable than passing a string to get the value of a key. Apart from that, it also provides a better solution when we want to have a default value when accessing a non-existing key from a dictionary.
If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above)