>>> 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'???
>>> 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']
.
From the documentation:
It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary).
In any order it pleases. Such is the nature of a dictionary. If you want it in a specific order, you have to do that yourself:
>>> d = {'pax': 1, 'george': 2, 'guido' : 3}
>>> d
{'pax': 1, 'george': 2, 'guido': 3}
>>> [(key,d[key]) for key in sorted(d)]
[('george', 2), ('guido', 3), ('pax', 1)]