what is the order of looping (for loop) in python dictionary

Question:

I am a bit confused with the output I get from the following.
I do not understand the order of the loop that is executed.

domains = { "de": "Germany", "sk": "Slovakia", "hu": "Hungary",
    "us": "United States", "no": "Norway"  }

for key in domains:
    print key

Output here is

sk
de
no
us
hu

but not

de
sk
hu
us
no

similarly, here

num = {1:"one",4:"two",23:"three",10:"four"}
for key in num:
    print key
output is
1
10
4
23

but not

1
4
23
10

Thanks for helping

Asked By: brain storm

||

Answers:

Python dictionaries do not preserve ordering:

Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions

A dictionary in CPython is implemented as a hash table to enable fast lookups and membership tests, and enumerating the keys or values happens in the order the items are listed in that table; where they are inserted depends on the hash value for the key and if anything was hashed to the same slot before already.

You’ll have to either sort the keys every time when displaying or use a a different type of data structure to preserve ordering. Python 2.7 or newer has a collections.OrderedDict() type, or you can use a list of two-value tuples (at which point lookups of individual key-value pairs is going to be slow).

Answered By: Martijn Pieters

The order is unspecified. It is, however, guaranteed to remain unchanged in the absence of modifications to the dictionary.

You can sort the keys when iterating:

for key in sorted(domains):
    print key

Finally, it may be useful to note that newer versions of Python have collections.OrderedDict, which preserves the insertion order.

Answered By: NPE

Python dictionaries don’t have an order. However, you can specify an order by using the sorted(domains) function. By default, it sorts using the key.

for key in sorted(domains):
    print key

will produce

de
hu
no
sk
us

If you want to order based on values, you can use something like sorted(domains.items(), key = lambda(k, v): (v, k)).

Answered By: siddharthlatest

If you want an ordered dictionary in Python you must use collections.OrderedDict

Answered By: mVChr

Dictionaries by definition have no order. That puts it into the dangerous “undefined behavior” zone – not a good idea to rely on it in anything you program, as it can change all of a sudden across implementations/instances. Even if it happens to work how you want now… it lays a landmine for you later.

Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.