+3  A: 

Dictionaries don't preserve the order of the keys. You could use a list of tuples instead of a dictionary.

Mark Byers
+6  A: 

A regular dictionary won't do, you'll have to use an ordered dictionary instead. Check out these links:

  1. PEP 372: Adding an ordered dictionary to collections
  2. Using an ordered dict as object dictionary in python -- an SO question to prove that people are using PEP 372's odict :-)
  3. Nicola Larosa & Michael Foord's odict module

Try the search term "python ordered dictionary" if you want to Google around for more. I remember seeing a number of ordered dict related questions here, on SO, so if the above links are inadequate for some reason, perhaps you can find something better in some other question.

Update: Mark's suggestion to use a list of tuples may be perfectly good, actually, but named tuples may be more convenient: a relevant fragment in the docs. Also, if you're planning to do some serialisation / deserialisation on your data and would like to do it really fast, check out Google's protocol buffers (Python tooling available).

Michał Marczyk
+6  A: 

I need to keep the order of the parameter, I mean, property comes first, then label until I get reouteDelay last.

Then you're simply doing things in the wrong order -- no need for ordered dictionaries! Try, instead, a tuple of pairs for cache, as follows:

def createNode(doc_, **param_):
    cache = ( ('p', 'property'), , ('l', 'label'), ('td', 'totalDelay'),
              ('rd', 'routeDelay'), ('ld', 'logicDelay') )
    for index, newIndex in cache:
        if index not in param_:
            continue
        value = param_[index]
        print newIndex, '=', value

This has exactly the same semantics as your version of createNode, plus the desired property of maintaining the order you wish, and performance is at least as good. By focusing on "keeping the dictionary ordered" you're focusing on the wrong problem (as is the case, alas, for most cases where people reach for "ordered dictionaries"!-).

Alex Martelli