Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In what order does python display dictionary keys? [duplicate]

Tags:

python

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

like image 625
Jackyjjc Avatar asked Dec 16 '10 06:12

Jackyjjc


People also ask

Are Python dictionary keys in 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.

How does Python handle duplicate keys?

You can not have duplicate keys in Python, but you can have multiple values associated with a key in Python. If you want to keep duplicate keys in a dictionary, you have two or more different values that you want to associate with same key in dictionary.


2 Answers

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

like image 101
Lennart Regebro Avatar answered Oct 19 '22 22:10

Lennart Regebro


In Python 2.7 you can use Ordered Dict.

like image 36
Fábio Diniz Avatar answered Oct 20 '22 00:10

Fábio Diniz