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

15,945

Solution 1

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

Solution 2

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

Solution 3

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.

Solution 4

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

Solution 5

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.

Share:
15,945
brain storm
Author by

brain storm

Updated on July 22, 2022

Comments

  • brain storm
    brain storm almost 2 years

    Possible Duplicate:
    Why is python ordering my dictionary like so?

    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

  • Martijn Pieters
    Martijn Pieters over 11 years
    @mgilson: yes, the sentence is indeed confusing and can be misinterpreted. Will correct.
  • ernie
    ernie over 11 years
    I think the first sentence is a bit misleading as well, especially as the quote states the exact opposite. You start off saying not ordered, and then the quotation states they are in an arbitrary order which is non-random. In other words, there is order, but it's just not immediately clear what the order is. A nitpick, but still somewhat confusing.
  • Martijn Pieters
    Martijn Pieters over 11 years
    @ernie: 'do not preserve ordering' then?
  • ernie
    ernie over 11 years
    No, they still preserve ordering. As in if you loop through the array multiple times, the order will be consistent (hence the non-random from the docs). Maybe it should just be the quote, with an emphasis on arbitrary order which is non-random?
  • mgilson
    mgilson over 11 years
    @ernie -- I think that it's OK to say they are not ordered. That's a pretty common way to say that the order cannot be depended on if you change the dictionary in any way (including creating it). Martijn -- 'do not preserve ordering` is just about as good as you can phrase it IMHO.