A MultiDict is a dictionary-like object that holds a number of values for a similar key, making it a helpful knowledge construction for processing varieties and question strings. It’s a subclass of the Python built-in dictionary and behaves equally. In some use circumstances, we might must convert a MultiDict to a nested dictionary, the place every key corresponds to a dictionary of values. On this article, we’ll focus on the steps required to transform a MultiDict to a nested dictionary in Python.
To start with, set up multidict library by writing the next command in your command line or terminal:
pip set up multidict
Steps to transform a MultiDict to a nested dictionary:
- Import multidict library
- Create a MultiDict utilizing the MultiDict() constructor
- Iterate over the objects within the MultiDict
- For every merchandise, verify if the important thing already exists within the nested dictionary.
- If the important thing exists, append the worth to the checklist of values related to the important thing.
- If the important thing doesn’t exist, create a brand new entry within the nested dictionary with the important thing and an inventory of values containing the worth from the MultiDict.
Instance 1:
Within the following instance, we convert a MultiDict to a nested dictionary.
Python3
|
Output:
On this instance, Create a MultiDict with keys ‘key1’ and ‘key2’ and a number of values. Iterate over the objects, add worth to the present key’s checklist or create a brand new entry with key and worth within the nested dictionary. Output is a nested dictionary with keys and lists of values related to every.

Instance 2:
Within the following instance, we convert a MultiDict to a nested dictionary.
Python3
|
Output:
On this instance, create a MultiDict with two keys ‘fruit’ and ‘colour’ with a number of values. Iterate over the objects, if the important thing exists, append its worth to the checklist, else create a brand new entry within the nested dictionary with the important thing and checklist of values. The ultimate output is a nested dictionary with keys and lists of values related to every key.
