Does the dictionary keys() function return the keys in any specific order?


#1

Question

Does the keys() function return dictionary keys in any specific order?

Answer

No, there is no guaranteed order for the list of keys returned by the keys() function. In most cases, the key list is returned in the same order as the insertion, however, that behavior is NOT guaranteed and should not be depended on by your program. A common practice is to pass keys() to the sorted() function to ensure that the list of keys is sorted before iteration.