Signup/Sign In

Print anagrams together in Python using List and Dictionary

In this tutorial, you will learn to find and print anagrams in a dictionary using list and dictionary concepts in Python. Anagrams are words that are formed by arranging the same letters in different orders. For example, cat and act are anagrams because they have the same characters which are just arranged differently.

Take a look at the sample input-output format.

Input: ['care', 'knee', 'race', 'keen']

Output: ['care', 'race', 'knee', 'keen']

Input: ['care', 'knee', 'race', 'keen']

Output: ['care', 'race', 'knee', 'keen']

The approach to solving this problem is to first traverse the list containing strings of words and sort each string in ascending order using the sorted() method. Then we will set the sorted value as the key and the original value as the value in the key.

Then we will check if the key is present or not in the dictionary. Set an empty list to the key and add value to it, if the key is already present then we will simply append the value.

Now each key will be containing a list of strings that are anagram together.

Algorithm

Follow the algorithm to understand the approach better.

Step 1- Define a function that will group anagrams

Step 2- Define an empty dictionary

Step 3- Traverse the dictionary

Step 4- Store the sorted strings in keys

Step 5- If a key is in the dictionary then add values to the dictionary

Step 6- Else create an empty list and add values in that dictionary

Step 7- Declare an empty string for storing the result

Step 8- Add the keys and values in the string

Step 9- Return this string as the result

Step 10- Declare a list of words

Step 11- Pass the list in the function and print the value returned by the function

Python Program

Look at the Python code to understand the implementation. In this program, we have used an empty dictionary to store the anagrams.

The sorted strings are stored in the key and their original value is stored in the value of this dictionary.

To add the value to the list, we have used the append() method. It returns a list after adding the element.

To get the key-value of the dictionary, we have used the items() method which returns keys and values of a given dictionary.

def Anagram(d1): 
      
    # empty dictionary for anagrams together 
    dict = {} 
  
    # traversal 
    for val in d1: 
          
        # sorts list
        key = ''.join(sorted(val)) 
          
        if key in dict.keys(): 
            dict[key].append(val) 
        else: 
            dict[key] = [] 
            dict[key].append(val) 
  
    # traverse dictionary and join keys together 
    result = "" 
    for key,value in dict.items(): 
        result = result + ' '.join(value) + ' '
  
    return result 
  
d1=['act', 'cat', 'silent','listen']
print("Words: ",d1)
print("Anagram: ",Anagram(d1))


Words: ['act', 'cat', 'silent', 'listen']
Anagram: act cat silent listen

Conclusion

In this tutorial, we have seen how to group anagrams using the dictionary, and list data structures in Python. To get the key or the value of a dictionary, we have used built-in methods like items(), keys() in the program.