0

I found something really strange when I try to return list(dict.values()).

 class Solution:
    def groupAnagrams(self, strs):  
        dict = {}
        for i in strs:
            key = ''.join(set(i))
            if key in dict.keys():
                dict[key].append(i)
            else:
                dict.update({key:[i]})
        return list(dict.values()) 
    #The input could be ["eat","tea","tan","ate","nat","bat"]
    #And it's supposed to get the result: [["bat"],["nat","tan"],["ate","eat","tea"]]

The thing is that , when I print list(dict.values()), the result is the same as the correct answer. But when I do return list(dict.values()), everytime the result is different. It could be [["nat"],["tan"],["eat","tea","ate"],["bat"]], or [['eat'], ['tea'], ['tan'], ['ate'], ['nat'], ['bat']] and etc. I am so confused about why this happened.

huier
  • 165
  • 2
  • 4
  • 12
  • Dictionaries are not stored in order, so the `dict.values()` list will give different orders. – Davy M Jan 05 '18 at 02:11
  • Which version of Python are you using? Basically, Python's dictionary does not maintain its insertion order. But it has been modified after Python 3.6+. See https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6 – dkato Jan 05 '18 at 02:26
  • 2
    The real problem is here `''.join(set(i))`. `set` is scrambling the order of the letters (for the reasons explained in the other comments). Sometimes they are being scrambled into the same order, so the anagrams are grouped correctly, but other times they are not so you see them sorted into different lists instead. Try `key = tuple(sorted(i))` – Patrick Haugh Jan 05 '18 at 02:30
  • I am using Python3 and runs the program on leetcode, so I am not sure whether it is over or below 3.6. But when I try it using Python 3.6 the list returned is also in a mess. – huier Jan 05 '18 at 02:32

0 Answers0