QQending QQending - 5 months ago 3x
Python Question

In what order does python display dictionary keys?

>>> D = {'a': 1, 'b': 2, 'c': 3}
>>> D
{'a': 1, 'c': 3, 'b': 2}

I just did this in the Python shell and I'm just wondering why the key 'c' would be after the key 'b'???


The order has to do with how they work internally and what order they end up in the hashtable. That in turn depends on the keys hash-value, the order they were inserted, and which Python implementation you are using.

The order is arbitrary (but not random) and it will never be useful to know which order it will be.

To get a sorted list of keys, just use sorted(D), which in your case will return ['a', 'b', 'c'].