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:
Python - Dictionary with Index as Value
Next article icon

Inverse Dictionary Values List – Python

Last Updated : 28 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given a dictionary and the task is to create a new dictionary where each element of the value lists becomes a key and the original keys are grouped as lists of values for these new keys.
For example: dict = {1: [2, 3], 2: [3], 3: [1]} then output will be {2: [1], 3: [1, 2], 1: [3]}

Using defaultdict

In this method we use defaultdict from the collections module to efficiently reverse the key-value mapping in a dictionary. It iterates through each key-value pair thus appending the key to the corresponding list in the result.

Python
from collections import defaultdict  d = {1: [2, 3], 2: [3], 3: [1], 4: [2, 1]}  # Reverse mapping res = defaultdict(list) for k, v in d.items():     for i in v:         res[i].append(k)  print(dict(res)) 

Output
{2: [1, 4], 3: [1, 2], 1: [3, 4]} 

Using setdefault()

This method uses the setdefault() method from the dictionary to initialize the list for each key that doesn’t exist in the result dictionary. It iterates through the original dictionary and appends the key to the list of each value.

Python
d = {1: [2, 3], 2: [3], 3: [1], 4: [2, 1]}  # Reverse mapping res = {} for k, v in d.items():     for i in v:         res.setdefault(i, []).append(k)  print(res) 

Output
{2: [1, 4], 3: [1, 2], 1: [3, 4]} 

Explanation: Outer loop processes each key-value pair and the setdefault() method ensures that each key in the result dictionary has a list initialized before appending the key to it.



Next Article
Python - Dictionary with Index as Value
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python dictionary-programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python Iterate Dictionary Key, Value
    In Python, a Dictionary is a data structure that stores the data in the form of key-value pairs. It is a mutable (which means once created we modify or update its value later on) and unordered data structure in Python. There is a thing to keep in mind while creating a dictionary every key in the dic
    3 min read
  • Python - Value Dictionary from Record List
    Sometimes, while working with Python Records lists, we can have problems in which, we need to reform the dictionary taking just values of the binary dictionary. This can have applications in many domains which work with data. Let us discuss certain ways in which this task can be performed. Method #1
    6 min read
  • Get Index of Values in Python Dictionary
    Dictionary values are lists and we might need to determine the position (or index) of each element within those lists. Since dictionaries themselves are unordered (prior to Python 3.7) or ordered based on insertion order (in Python 3.7+), the concept of "index" applies to the values—specifically whe
    3 min read
  • Set from Dictionary Values - Python
    The task is to extract unique values from a dictionary and convert them into a set. In Python, sets are unordered collections that automatically eliminate duplicates. The goal is to extract all the values from the dictionary and store them in a set. For example, given a dictionary like d = {'A': 4,
    3 min read
  • Python - Dictionary with Index as Value
    We are having a list we need to find index of each element and store it in form of dictionary. For example, a = ['a', 'b', 'c', 'd'] we need to find index of each elements in list so that output should be {'a': 0, 'b': 1, 'c': 2, 'd': 3}. Using Dictionary ComprehensionWe can use dictionary comprehen
    2 min read
  • Python Convert Dictionary to List of Values
    Python has different types of built-in data structures to manage your data. A list is a collection of ordered items, whereas a dictionary is a key-value pair data. Both of them are unique in their own way. In this article, the dictionary is converted into a list of values in Python using various con
    3 min read
  • Convert Dictionary Value list to Dictionary List Python
    Sometimes, while working with Python Dictionaries, we can have a problem in which we need to convert dictionary list to nested records dictionary taking each index of dictionary list value and flattening it. This kind of problem can have application in many domains. Let's discuss certain ways in whi
    9 min read
  • Python - Values Frequency Index List
    Sometimes, while working with Python tuples, we can have a problem in which we need to extract the frequency of each value in tuple. This has been solved earlier. We can have a modification in which we need to create list in which index represents the key and value of it represents the frequency of
    4 min read
  • Python - Assign Reversed Values in Dictionary
    Given a dictionary, assign each key, values after reverting the values of dictionary. Input : {1 : 4, 2 : 5, 3 : 6} Output : {1 : 6, 2 : 5, 3 : 4} Explanation : Value order changed, 4, 5, 6 to 6, 5, 4. Input : {1 : 5, 2 : 5, 3 : 5} Output : {1 : 5, 2 : 5, 3 : 5} Explanation : Same values, no visible
    4 min read
  • Reverse Dictionary Keys Order - Python
    We are given a dictionary and our task is to reverse the order of its keys. This means if we have a dictionary like {'a': 1, 'b': 2, 'c': 3} then the output will be {'c': 3, 'b': 2, 'a': 1}. This can be done using methods like reversed(), dictionary comprehensions, or OrderedDict. Let's explore thes
    4 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