Take the 2-minute tour ×

I have a dictionary, and I want to use the items (key,value) to generate a single string, which I will pass argument to another script on the command line.

Snippet illustrates further:

args = { 'arg1': 100, 'arg2': 234 }

I want to create the string:

--arg1=100 --arg2=234

from the dictionary.

The naive (expensive) way to do that would be to loop through the items in the dictionary, building the string as I went along.

Is there a more pythonic way of doing this?

share|improve this question

3 Answers 3

up vote 4 down vote accepted

You need a loop, but you can do it concisely:

" ".join("--%s=%s" % item for item in args.iteritems())

(for Python 2. For Python 3, change iteritems to items)

share|improve this answer
items() works for me - and I'm using 2.6.5 –  Homunculus Reticulli May 13 '12 at 20:31
items() will work, it just makes an unneeded list along the way. –  Ned Batchelder May 13 '12 at 20:44
@NedBatchelder Not in Python 3, right? –  Lev Levitsky May 14 '12 at 6:49
Right: "items" will work in either 2 or 3. "iteritems" will work in Py2, but does not exist in Py3. "items" in Py3 is the same as "iteritems" in Py2, and does not create an explicit list of items. –  Ned Batchelder May 14 '12 at 13:12
' '.join('--%s=%s' % (k, v) for (k, v) in args.items())
share|improve this answer
Expensive tuple unpack is not needed... –  JBernardo May 13 '12 at 20:10

Since you plan to pass it to another script and probably do so using the subprocess module: Do not create a string at all!

args = ['/path/to/your/script'] + ['--%s=%s' % item for item in args.iteritems()]

You can pass this array to subprocess.call() (or .Popen() etc.) and by not using an argument string you can ensure that even spaces, quotes, etc. won't cause any issues.

share|improve this answer
+1 for the info on .Popen - I wasn't aware of that. I'll use that for later. –  Homunculus Reticulli May 13 '12 at 20:25

Your Answer


