0

I'm running this code from Dive Into Python:

def buildConnectionString(params):
    """Build a connection string from a dictionary of parameters.
    Returns string."""
    return ";".join(["%s=%s" % (k, v) for k, v in params.items()])
if __name__ == "__main__":
    myParams = {"server":"mpilgrim", \
                "database":"master", \
                "uid":"sa", \
                "pwd":"secret" \
                }
    print buildConnectionString(myParams)

The book says its output should be:

server=mpilgrim;uid=sa;database=master;pwd=secret

But when I run it it comes out in reverse:

pwd=secret;database=master;uid=sa;server=mpilgrim

Any ideas why?

5
  • 2
    2 comments on style here. 1- the backslashes you're using for line continuation are unnecessary. 2- the list comprehension could be turned into a generator simply by removing the square brackets. (e.g. ';'.join( "%s=%s" % (k, v) for k, , in params.items() ) Commented Jul 30, 2012 at 13:46
  • 2
    Also, PEP8 favors underscore delimited function names, not camel case (build_connection_string and my_params, not buildConnectionString and myParams). Not a requirement, but when working in Python, sticking with PEP8 generally makes life easier. Commented Jul 30, 2012 at 13:49
  • @sr2222 -- Good point on PEP8 Commented Jul 30, 2012 at 13:50
  • since we are dishing out suggestions here I will add one: new string formatting: '{0}{1}'.format(k, v) is preferred to % formatting "%s=%s" % (k, v) Commented Jul 30, 2012 at 13:55
  • @mgilson, sr222, jamylak - Not my code.. but thanks Commented Jul 30, 2012 at 18:11

2 Answers 2

7

The fact that it is in exactly reverse order is really just a coincidence. Run the code with a different version/implementation of python and you'll likely get a different ordering. The reason for this is because in python dictionaries are not ordered so the order of the ouput of your function is not well defined. (The order that you put things into the dictionary is not the order that they are yielded as you iterate over the dictionary).

If you want a specific order, you can sort parames.items() using the builtin sorted function (optionally using the key keyword to tell sorted how to sort the items). Another option is to use an OrderedDict from the collections module which appeared in python2.7 (as pointed out by sr2222).

Sign up to request clarification or add additional context in comments.

Comments

3

Because you are printing a dictionary, and dictionaries are unordered. The order a dictionary is iterated through is dependent on a number of factors including interpreter type, interpreter version, and OS. If you want it to come out the same order you put it in, you have to use collections.OrderedDict instead. Alternatively, as mgilson said in his answer, you could sort the dictionary contents before printing it, but given that the order you want is not alphabetical, it's probably more trouble than it is worth.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.