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.
The order is indeed not guaranteed in Python 3.5 and earlier, but is the same as the insertion order (although not documented), in Python 3.6, and documented in 3.7 and beyond.
In the exercise you are referring to, we are asked to create a variable containing the keys of a dictionary and to then print this variable. Which steps are (not) performed in the two code snippets you provide?
There are parentheses after keys. Does It mean we can choose some specific keys?
If we want to choose specific keys do we have to iterate over the keys.
Keys is a method and therefore requires the function style parantheses to call it: .keys() but it doesnât take any arguments.Specific keys can be accessed with the dict[key] syntax so it isnât necessary to iterate through them (the look-up is done for you). For multiple specific keys you would need some sort of looping/mapping/unpacking or similar but itâs not the ideal way to use dictionaries.
what you are trying to get is a âlist of name of keysâ but expected result is a âlist of dictionary keysâ.
your result is not matching the expected result.
Also, the example doesnât fill an empty list with a for statement. To execute the code you wrote, you would need to use .append instead of += (which works on strings, but not lists?). Correct me if Iâm wrong.
Since Python 3.7 was released as per my undestanding, dictionaries now return keys in order.
The locals() dictionary now displays in the lexical order that variables were defined. Previously, the order was undefined. (Contributed by Raymond Hettinger in bpo-32690.)
The mention of Python 3.6 was an implementation detail of CPython3.6; it technically followed an order but it had the potential to change in future releases and the program may misbehave if run with non CPython versions (Jython, PyPy etc.). Relying on implementation details has always been considered bad practice (liable to change, less portable etc. etc.).
With Python 3.7 a dict was guaranteed to be insertion ordered (order based on when items are added) as part of the Python language specification and this should be true of any implementation of Python from 3.7 onwards.