0

I am using a recursive code as below:

    def dfs(self, hash_map):
        ans = 1
        for key,value in hash_map.items():
            if value > 0:
                hash_map[key] = hash_map[key] - 1
                ans = ans + self.dfs(hash_map)
                hash_map[key] = value 
        return ans

So will the list returned by items() method in the dictionary retain the order?

unknown29
  • 47
  • 5
  • See if this answer your question: https://stackoverflow.com/questions/835092/python-dictionary-are-keys-and-values-always-the-same-order – Dani Mesejo Oct 18 '19 at 01:21

2 Answers2

0

Not necessarily, it depends on what version of Python you're using. check out OrderedDict

From the docs:

Ordered dictionaries are just like regular dictionaries but have some extra capabilities relating to ordering operations. They have become less important now that the built-in dict class gained the ability to remember insertion order (this new behavior became guaranteed in Python 3.7).

Nick Martin
  • 711
  • 2
  • 17
0

If you were relying on the order of keys in a Python dictionary or set, then don't. Python uses a hash table to implement these types and their order depends on the insertion and deletion history as well as the random hash seed.

More details with about the fact can be found here: hash function in Python 3.3 returns different results between sessions

donglinjy
  • 922
  • 4
  • 13