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 the list alphabetically in a dictionary
Next article icon

Print anagrams together in Python using List and Dictionary

Last Updated : 11 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

An anagram is a word or phrase formed by rearranging the letters of another word or phrase, using all the original letters exactly once. The task of grouping anagrams together in Python can be efficiently solved using lists and dictionaries. The key idea is to process each word by sorting its characters, which helps identify anagrams as they will share the same sorted representation. By using a dictionary, we can store these sorted words as keys and group the original words as values, ensuring that all anagrams appear together.

For example, given a list a = [‘bat’, ‘nat’, ‘tan’, ‘ate’, ‘eat’, ‘tea’], the expected output would be:[[‘bat’], [‘nat’, ‘tan’], [‘ate’, ‘eat’, ‘tea’]].

Python
dict = {} # initialize empty dictionary  a = ['bat', 'nat', 'tan', 'ate', 'eat', 'tea']  # Iterate through each word for word in a:     sort_word = ''.join(sorted(word))      if sort_word in dict:         dict[sort_word].append(word)     else:         dict[sort_word] = [word]  res = list(dict.values()) print(res) 

Output
[['bat'], ['nat', 'tan'], ['ate', 'eat', 'tea']] 

Explanation:

  • sorted(word) arranges the letters of the word in alphabetical order and ”.join(sorted(word)) converts the sorted list of characters back into a string.
  • If sort_word is already a key in dict, append the current word to its corresponding
  • Otherwise, create a new entry in dict with sort_word as the key and the word as the first element of a new list.
  • list(dict.values()) extracts those lists and stores them in res.


Next Article
Python | Sort the list alphabetically in a dictionary
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
  • DSA
  • Python
  • Strings
  • anagram
  • Python dictionary-programs
  • Python list-programs
  • python-dict
  • python-list
Practice Tags :
  • anagram
  • python
  • python-dict
  • python-list
  • Strings

Similar Reads

  • How to convert a MultiDict to nested dictionary using Python
    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 d
    3 min read
  • Add new keys to a dictionary in Python
    In this article, we will explore various methods to add new keys to a dictionary in Python. Let's explore them with examples: Using Assignment Operator (=)The simplest way to add a new key is by using assignment operator (=). [GFGTABS] Python d = {"a": 1, "b": 2} d["c"]
    2 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
  • Python | Sort the list alphabetically in a dictionary
    In Python Dictionary is quite a useful data structure, which is usually used to hash a particular key with value, so that they can be retrieved efficiently. Let's see how to sort the list alphabetically in a dictionary. Sort a List Alphabetically in PythonIn Python, Sorting a List Alphabetically is
    3 min read
  • Ways to create a dictionary of Lists - Python
    A dictionary of lists is a type of dictionary where each value is a list. These dictionaries are commonly used when we need to associate multiple values with a single key. Initialize a Dictionary of ListsThis method involves manually defining a dictionary where each key is explicitly assigned a list
    3 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
  • Generate a graph using Dictionary in Python
    Prerequisite - Graphs To draw graph using in built libraries - Graph plotting in PythonIn this article, we will see how to implement graph in python using dictionary data structure in python. The keys of the dictionary used are the nodes of our graph and the corresponding values are lists with each
    6 min read
  • Combine similar characters in Python using Dictionary Get() Method
    Let us see how to combine similar characters in a list. Example : Input : ['g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's'] Output : ['gg', 'eeee', 'kk', 'ss', 'f', 'o', 'r'] We will be using the get() method of the dictionary class. dictionary.get() The get() method returns the valu
    3 min read
  • Python | Convert list of tuple into dictionary
    Given a list containing all the element and second list of tuple depicting the relation between indices, the task is to output a dictionary showing the relation of every element from the first list to every other element in the list. These type of problems are often encountered in Coding competition
    8 min read
  • Scraping And Finding Ordered Words In A Dictionary using Python
    What are ordered words? An ordered word is a word in which the letters appear in alphabetic order. For example abbey & dirt . The rest of the words are unordered for example geeks The task at hand This task is taken from Rosetta Code and it is not as mundane as it sounds from the above descripti
    3 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