2

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

I have this fully working code, but it acts strangely: items in dictionary are iterated not sequentially but somehow randomly, why is that?:

#!/usr/bin/python

newDict = {}
lunar = {'a':'0','b':'0','c':'0','d':'0','e':'0','f':'0'}
moon = {'a':'1','d':'1','c':'1'}

for il, jl in lunar.items():
    print "lunar: " + il + "." + jl 
    for im, jm in moon.items():
        if il == im:
            newDict[il] = jm
            break
        else:
            newDict[il] = jl

print newDict

Output:

lunar: a.0
lunar: c.0
lunar: b.0
lunar: e.0  
lunar: d.0
lunar: f.0
{'a': '1', 'c': '1', 'b': '0', 'e': '0', 'd': '1', 'f': '0'}
Community
  • 1
  • 1
  • 1
    because dictionary is not a sequence. it doesn't have order. – SilentGhost Nov 13 '12 at 12:43
  • And [Python dictionary, keep keys/values in same order as declared](http://stackoverflow.com/q/1867861) – Martijn Pieters Nov 13 '12 at 12:45
  • If you really really want to use this dict and to print it sorted, you could also use : `print "{%s}" % (", ".join(["'%s': '%s'" % (k,v) for (k,v) in sorted(newDict.iteritems(),key=itemgetter(0))]))`. By the way, you could also construct `newDict` with : `newDict = dict([(k,k in moon and moon[k] or v) for (k,v) in lunar.iteritems()])` – Julien Vivenot Nov 13 '12 at 13:05

2 Answers2

5

Dictionaries do not save input order. You can try OrderedDict class from collections module - OrderedDict Examples and Recipes

Noordeen
  • 1,547
  • 20
  • 26
alexvassel
  • 10,600
  • 2
  • 29
  • 31
3

Python dict is not ordered. For performance reasons, it is more efficient for the implementation to forget the order in which you added items.

As the documentation states:

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.

If you need an ordered dictionary, you can use OrderedDict.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490