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’???

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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'].

Method 2

In Python 2.7 you can use Ordered Dict.

Method 3

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

Method 4

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)]


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x