2

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?

3 Answers 3

4

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)

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

2 Comments

items() will work, it just makes an unneeded list along the way.
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.
2
' '.join('--%s=%s' % (k, v) for (k, v) in args.items())

Comments

2

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.

1 Comment

+1 for the info on .Popen - I wasn't aware of that. I'll use that for later.

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.