Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Convert Lists to Nested Dictionary - Python
Next article icon

How to convert a MultiDict to nested dictionary using Python

Last Updated : 24 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A MultiDict is a dictionary-like object that holds multiple values for the same key, making it a useful data structure for processing forms and query strings. It is a subclass of the Python built-in dictionary and behaves similarly. In some use cases, we may need to convert a MultiDict to a nested dictionary, where each key corresponds to a dictionary of values. In this article, we will discuss the steps required to convert a MultiDict to a nested dictionary in Python.

First of all, install multidict library by writing the following command in your command line or terminal:

pip install multidict

Steps to convert a MultiDict to a nested dictionary:

  1. Import multidict library
  2. Create a MultiDict using the MultiDict() constructor
  3. Iterate over the items in the MultiDict
  4. For each item, check if the key already exists in the nested dictionary.
  5. If the key exists, append the value to the list of values associated with the key.
  6. If the key does not exist, create a new entry in the nested dictionary with the key and a list of values containing the value from the MultiDict.

Example 1:

In the following example, we convert a MultiDict to a nested dictionary.

Python3
# import multidict from multidict import MultiDict  # create a MultiDict data = MultiDict([('key1', 'value1'), ('key2', 'value2'),                   ('key1', 'value3')])  # initialize a nested dictionary nested_dict = {}  # iterate over the items in the MultiDict for key, value in data.items():     # check if the key exists in the nested dictionary     if key in nested_dict:         # append the value to the list of values         # associated with the key         nested_dict[key].append(value)     else:         # create a new entry in the nested dictionary         # with the key and a list of values         nested_dict[key] = [value]  # output the nested dictionary print(nested_dict) 

Output:

In this example, Create a MultiDict with keys 'key1' and 'key2' and multiple values. Iterate over the items, add value to the existing key's list or create a new entry with key and value in the nested dictionary. Output is a nested dictionary with keys and lists of values associated with each.

 

Example 2:

In the following example, we convert a MultiDict to a nested dictionary.

Python3
# import multidict from multidict import MultiDict  # create a MultiDict data = MultiDict([('fruit', 'apple'), ('color', 'red'),                   ('fruit', 'banana'), ('color', 'yellow')])  # initialize a nested dictionary nested_dict = {}  # iterate over the items in the MultiDict for key, value in data.items():     # check if the key exists in the nested dictionary     if key in nested_dict:         # append the value to the list of values         # associated with the key         nested_dict[key].append(value)     else:         # create a new entry in the nested dictionary         # with the key and a list of values         nested_dict[key] = [value]  # output the nested dictionary print(nested_dict) 

Output:

In this example, create a MultiDict with two keys 'fruit' and 'color' with multiple values. Iterate over the items, if the key exists, append its value to the list, else create a new entry in the nested dictionary with the key and list of values. The final output is a nested dictionary with keys and lists of values associated with each key.

 

Next Article
Convert Lists to Nested Dictionary - Python
author
mukulsomukesh
Improve
Article Tags :
  • Python
Practice Tags :
  • python

Similar Reads

  • Convert Lists to Nested Dictionary - Python
    The task of converting lists to a nested dictionary in Python involves mapping elements from multiple lists into key-value pairs, where each key is associated with a nested dictionary. For example, given the lists a = ["gfg", "is", "best"], b = ["ratings", "price", "score"], and c = [5, 6, 7], the g
    3 min read
  • How to convert NumPy array to dictionary in Python?
    The following article explains how to convert numpy array to dictionary in Python. Array in Numpy is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. In Numpy, number of dimensions of the array is called rank of the array. A tuple of integers givi
    3 min read
  • Create a Nested Dictionary from Text File Using Python
    We are given a text file and our task is to create a nested dictionary using Python. In this article, we will see how we can create a nested dictionary from a text file in Python using different approaches. Create a Nested Dictionary from Text File Using PythonBelow are the ways to Create Nested Dic
    3 min read
  • How To Convert Python Dictionary To JSON?
    In Python, a dictionary stores information using key-value pairs. But if we want to save this data to a file, share it with others, or send it over the internet then we need to convert it into a format that computers can easily understand. JSON (JavaScript Object Notation) is a simple format used fo
    7 min read
  • Convert Two Lists into a Dictionary - Python
    We are given two lists, we need to convert both of the list into dictionary. For example we are given two lists a = ["name", "age", "city"], b = ["Geeks", 30,"Delhi"], we need to convert these two list into a form of dictionary so that the output should be like {'name': 'Geeks', 'age': 30, 'city': '
    3 min read
  • Convert a list of Tuples into Dictionary - Python
    Converting a list of tuples into a dictionary involves transforming each tuple, where the first element serves as the key and the second as the corresponding value. For example, given a list of tuples a = [("a", 1), ("b", 2), ("c", 3)], we need to convert it into a dictionary. Since each key-value p
    3 min read
  • How To Convert Generator Object To Dictionary In Python
    We are given a generator object we need to convert that object to dictionary. For example, a = (1, 2, 3), b = ('a', 'b', 'c') we need to convert this to dictionary so that the output should be {1: 'a', 2: 'b', 3: 'c'}. Using a Generator ExpressionA generator expression can be used to generate key-va
    3 min read
  • Convert nested Python dictionary to object
    Let us see how to convert a given nested dictionary into an object Method 1 : Using the json module. We can solve this particular problem by importing the json module and use a custom object hook in the json.loads() method. C/C++ Code # importing the module import json # declaringa a class class obj
    2 min read
  • How to Create a Dictionary in Python
    The task of creating a dictionary in Python involves storing key-value pairs in a structured and efficient manner, enabling quick lookups and modifications. A dictionary is an unordered, mutable data structure where each key must be unique and immutable, while values can be of any data type. For exa
    3 min read
  • Python - Convert Dictionary Object into String
    In Python, there are situations where we need to convert a dictionary into a string format. For example, given the dictionary {'a' : 1, 'b' : 2} the objective is to convert it into a string like "{'a' : 1, 'b' : 2}". Let's discuss different methods to achieve this: Using strThe simplest way to conve
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences