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

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.

8 Likes

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.

27 Likes

How would the sorted() function be used? Do you have some sample code?

3 Likes

can i know what’s wrong in my solution ?
Capture

sorted_keys = sorted(my_dict.keys())
2 Likes

You simply want the following on line 4:

users = user_ids.keys()

and eliminate the loop on lines 6-7.

3 Likes

and what it the differs between the answer on the example
for student in test_scores.keys():
print(student)

and the answer on the test
users = user_ids.keys()
print(users)

and why we can’t use the first answer

1 Like

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?

1 Like

In what way is the list sorted?
I can’t see it being sorted alphabetically or by value nor length of word.

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.

3 Likes

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.
:grinning:

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.)
2 Likes

As the error says, it is expecting a dict_keys type but your solution is outputting the list type.

i don’t understand is it in order in python 3.7 and later or not ?

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.

3 Likes

Thank you very much i have understood

1 Like

Use append() instead +=. And replace square brackets from ‘i’.

a = {"a": 1, "b": 2, "d": 4, "c": 3, "e": 5, "f": 6}
b = []
for i in a.keys():
    b.append(i)
print(b)

Since .keys() is already an enumerable, we can transform it to a list with the splat operator…

>>> a = {"a": 1, "b": 2, "d": 4, "c": 3, "e": 5, "f": 6}
>>> b = [*a.keys()]
>>> b
['a', 'b', 'd', 'c', 'e', 'f']

>>> c = [*a.values()]
>>> c
[1, 2, 4, 3, 5, 6]
>>> d = [*a.items()]
>>> d
[('a', 1), ('b', 2), ('d', 4), ('c', 3), ('e', 5), ('f', 6)]

3 Likes