+

Print anagrams together in Python using List and Dictionary

Examples:

 Input: arr = [`cat`,` dog`, `tac`,` god`, `act`] Output:` cat tac act dog god` 

This problem has an existing solution, please refer to given the sequence of words, print all anagrams along with links ... We`ll solve this problem in python using the data structures

# Function to return all anagrams together

def allAnagram ( input ):

 

# an empty dictionary that contains subsets

# all anagrams together

dict = {}

 

# list of strings

for strVal in input :

 

  # sorted (iterable) method accepts any

# iterate and return a list of items

  # in ascending order

key = ` `.join ( sorted (strV al))

 

# now check for the key in the dictionary

# or not. If so, just add

# strVal to the list of matching

# key If not, display empty list on

# and then start adding values ​​

if key in dict . keys ():

dict [key] .append (strVal)

else :

dict [key] = [] < / code>

dict [key] .append ( strVal)

 

# go through dictionary and concatenate values ​​

Number of keys together

output = " "

  for key, value in dict . iteritems ():

output = output + `` . join (value)  + ``

  

return output

 
# Driver function

if __ name__ = = " __ main__ " :

  input = [ `cat` , `dog` , ` tac` , `god` , ` act` ]

  print allAnagram ( input )

Exit:

 `cat tac act dog god` 

This article courtesy of Shashankom Mishra (Gullu) . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you`d like to share more information on the topic discussed above.

Get Solution for free from DataCamp guru