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 - Sort Dictionary by Values and Keys
Next article icon

Python program to Swap Keys and Values in Dictionary

Last Updated : 17 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Dictionary is quite a useful data structure in programming that is usually used to hash a particular key with value so that they can be retrieved efficiently. Let’s discuss various ways of swapping the keys and values in Python Dictionary. 

Method#1 (Does not work when there are multiple same values): One naive solution maybe something like just swapping the key and values respectively. 

Example:

Input : {'A': 67, 'B': 23, 'C': 45, 'D': 56, 'E': 12, 'F': 69, 'G': 67, 'H': 23}  Output: {67: 'G', 69: 'F', 23: 'H', 56: 'D', 12: 'E', 45: 'C'}

Python3




# Python3 code to demonstrate 
# swap of key and value
   
# initializing dictionary
old_dict = {'A': 67, 'B': 23, 'C': 45, 'D': 56, 'E': 12, 'F': 69, 'G': 67, 'H': 23}
 
new_dict = dict([(value, key) for key, value in old_dict.items()])
   
# Printing original dictionary
print ("Original dictionary is : ")
print(old_dict)
 
print()
 
# Printing new dictionary after swapping keys and values
print ("Dictionary after swapping is :  ")
print("keys: values")
for i in new_dict:
    print(i, " :  ", new_dict[i])
 
 

Output

Original dictionary is :  {'D': 56, 'E': 12, 'C': 45, 'A': 67, 'F': 69, 'H': 23, 'B': 23, 'G': 67}  Dictionary after swapping is :   keys: values 67  :   G 69  :   F 23  :   B 56  :   D 12  :   E 45  :   C

But there is a problem with this approach. In our example, we have multiple keys with the same values i.e. (‘A’, 67) and (‘G’, 67) and the other keys having the same values are (‘B’, 23) and (‘H’, 23). But in the result, we obtained only one key from each. i.e we obtained only (‘G’, 67) and (‘B’, 23). So, here’s another approach to deal with this problem: 

Method#2 (Handles multiple same values): In this approach, we will check if the value is already present or not. If present then just append it to the list. 

Example:

Input : {'A': 67, 'B': 23, 'C': 45, 'E': 12, 'F': 69, 'G': 67, 'H': 23} Output: {45: ['C'], 67: ['A', 'G'], 12: ['E'], 69: ['F'], 23: ['B', 'H']}

Python3




# Python3 code to demonstrate 
# swap of key and value
   
# initializing dictionary
old_dict = {'A': 67, 'B': 23, 'C': 45, 'E': 12, 'F': 69, 'G': 67, 'H': 23}
 
# Printing original dictionary
print ("Original dictionary is : ")
print(old_dict)
 
print()
new_dict = {}
for key, value in old_dict.items():
   if value in new_dict:
       new_dict[value].append(key)
   else:
       new_dict[value]=[key]
 
# Printing new dictionary after swapping
# keys and values
print ("Dictionary after swapping is :  ")
print("keys: values")
for i in new_dict:
    print(i, " :", new_dict[i])
 
 

Output

Original dictionary is :  {'F': 69, 'G': 67, 'H': 23, 'A': 67, 'C': 45, 'B': 23, 'E': 12}  Dictionary after swapping is :   keys: values 45  : ['C'] 67  : ['G', 'A'] 12  : ['E'] 69  : ['F'] 23  : ['H', 'B']

Method 3: Using List Comprehension and Set

Python3




# Python code to swap key and value
# of dictionary using list comprehension
# and Set
 
dict1 = {"a": 1, "b": 2, "c": 3, "d": 2}
dict2 = {}
 
dict2 = dict([(v, [k for k, v1 in dict1.items() if v1 == v])
              for v in set(dict1.values())])
 
print(dict2)
 
 
Output
{1: ['a'], 2: ['b', 'd'], 3: ['c']}

Time Complexity: O(n)
Auxiliary Space: O(n)

Method 4: Using get() Method

Python3




# Python code to swap key and value
# of dictionary using Get() Method
 
dict1 = {"a": 1, "b": 2, "c": 3, "d": 2}
dict2 = {}
 
for k, v in dict1.items():
    dict2[v] = dict2.get(v, []) + [k]
 
print(dict2)
 
 
Output
{1: ['a'], 2: ['b', 'd'], 3: ['c']}

Time complexity: O(n), where n is the number of key-value pairs in the dictionary. 
Auxiliary space: O(n), where n is the number of key-value pairs in the dictionary.

Method 5: Using Dictionary SetDefault() Method

Python3




# Python code to swap key and value
# of dictionary using Dictionary
# Setdefault() Method
 
dict1 = {"a": 1, "b": 2, "c": 3, "d": 2}
dict2 = {}
 
for i in dict1:
    dict2.setdefault(dict1[i], []).append(i)
 
print(dict2)
 
 
Output
{1: ['a'], 2: ['b', 'd'], 3: ['c']}

Method 6: Using DefaultDict

Python3




# Python code to swap key and value
# of dictionary using defaultdict
 
from collections import defaultdict
 
dict1 = {"a": 1, "b": 2, "c": 3, "d": 2}
 
dict2 = defaultdict(list)
 
{dict2[v].append(k) for k, v in dict1.items()}
 
print(dict(dict2))
 
 
Output
{1: ['a'], 2: ['b', 'd'], 3: ['c']}

Time complexity: The time complexity of the given program is O(n), where n is the number of items in the dictionary. .

Auxiliary space: The auxiliary space used by the program is O(n), where n is the number of items in the dictionary.



Next Article
Python - Sort Dictionary by Values and Keys

V

Vishal Chaudhary 2
Improve
Article Tags :
  • Python
  • Python Programs
  • Python dictionary-programs
  • python-dict
Practice Tags :
  • python
  • python-dict

Similar Reads

  • Add a key value pair to Dictionary in Python
    The task of adding a key-value pair to a dictionary in Python involves inserting new pairs or updating existing ones. This operation allows us to expand the dictionary by adding new entries or modify the value of an existing key. For example, starting with dictionary d = {'key1': 'geeks', 'key2': 'f
    3 min read
  • Python Print Dictionary Keys and Values
    When working with dictionaries, it's essential to be able to print their keys and values for better understanding and debugging. In this article, we'll explore different methods to Print Dictionary Keys and Values. Example: Using print() Method [GFGTABS] Python my_dict = {'a': 1, 'b'
    2 min read
  • Python - Swap ith and jth key's value in dictionary
    Given a dictionary, perform swapping of ith and jth index key's value. Input : test_dict = {"Gfg": 2, "is": 4, "best": 7, "for": 9, "geeks": 10}, i, j = 1, 4 Output : {'Gfg': 2, 'is': 10, 'best': 7, 'for': 9, 'geeks': 4} Explanation : Values of "is" and "geeks" swapped.Input : test_dict = {"Gfg": 2,
    6 min read
  • Python - Sort Dictionary by Values and Keys
    Given a dictionary, sort according to descended values, if similar values, then by keys lexicographically. Input : test_dict = {"gfg" : 1, "is" : 1, "best" : 1, "for" : 1, "geeks" : 1} Output : {"best" : 1, "is" : 1, "for" : 1, "geeks" : 1, "gfg" : 1} Explanation : All values are equal, hence lexico
    3 min read
  • Python - Sort Dictionary key and values List
    Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform the sorting of it, wrt keys, but also can have a variation in which we need to perform a sort on its values list as well. Let's discuss certain way in which this task can be performed. Input : test_d
    6 min read
  • Python Dictionary Add Value to Existing Key
    The task of adding a value to an existing key in a Python dictionary involves modifying the value associated with a key that is already present. Unlike adding new key-value pairs, this operation focuses on updating the value of an existing key, allowing us to increment, concatenate or otherwise adju
    2 min read
  • Python - Mapping Key Values to Dictionary
    We are given two list and we need to map key to values of another list so that it becomes dictionary. For example, we are given two list k = ['a', 'b', 'c'] and v = [1, 2, 3] we need to map the keys of list k to the values of list v so that the resultant output should be {'a': 1, 'b': 2, 'c': 3}. Us
    3 min read
  • Iterate Through Dictionary Keys And Values In Python
    In Python, a Dictionary is a data structure where the data will be in the form of key and value pairs. So, to work with dictionaries we need to know how we can iterate through the keys and values. In this article, we will explore different approaches to iterate through keys and values in a Dictionar
    2 min read
  • Python | Ways to change keys in dictionary
    Given a dictionary, the task is to change the key based on the requirement. Let's see different methods we can do this task in Python. Example: initial dictionary: {'nikhil': 1, 'manjeet': 10, 'Amit': 15} final dictionary: {'nikhil': 1, 'manjeet': 10, 'Suraj': 15} c: Amit name changed to Suraj.Metho
    3 min read
  • Python - Assign values to initialized dictionary keys
    Sometimes, while working with python dictionaries, we can have a problem in which we need to initialize dictionary keys with values. We save a mesh of keys to be initialized. This usually happens during web development while working with JSON data. Lets discuss certain ways in which this task can be
    5 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