Homunculus Reticulli
Homunculus Reticulli

Reputation: 68416

Pythonic way to create a command args strings from key => values sored in a dictionary

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?

Upvotes: 2

Views: 146

Answers (3)

ThiefMaster
ThiefMaster

Reputation: 318508

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.

Upvotes: 2

Ned Batchelder
Ned Batchelder

Reputation: 375574

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)

Upvotes: 4

Ismail Badawi
Ismail Badawi

Reputation: 37177

' '.join('--%s=%s' % (k, v) for (k, v) in args.items())

Upvotes: 2

Related Questions