Using dot notation in Python dicts
Dynamically convert a dictionary object into a generic Python object
Have you ever interacted with a REST API that returned JSON data? In Python, one of the most popular libraries for making HTTP requests and handling responses is the requests
library. The data returned in the response can be accessed using the response.text
property, which returns a string in JSON format. This data can be easily converted into a Python dictionary using the response.json()
method, allowing for easy access to the individual items. For example:
import requests
response = requests.get(url=url)
data = response.json()
This will return the data as a dict and we can access the items with
x = data["key_nested_dict"]["nested1"]["deep"]
But what if we wanted to access the data using “dot notation” such as:
x = data_obj.key_nested_dict.nested1.deep
In this guide, I’ll demonstrate how to dynamically convert a dictionary object into a generic Python object so that we can use dot notation. My inspiration for this guide comes from a popular Stack Overflow question I came across some time ago. You are welcome to use this solution for any purpose you may have.