pythondictionarycsstidy

python:how to output the Dictionary key and value as the following style using python 2.6?


args =[]
csstidy_opts = {
    '--allow_html_in_templates':False,
    '--compress_colors':False,
    '--compress_font-weight':False,
    '--discard_invalid_properties':False,
    '--lowercase_s':false,
    '--preserve_css':false,
    '--remove_bslash':false,
    '--remove_last_;':false,
    '--silent':False,
    '--sort_properties':false,
    '--sort_selectors':False,
    '--timestamp':False,
    '--merge_selectors':2,  
}
for key value in csstidy_opts.item():
   args.append(key)
   args.append(':')
   args.append(value)

i want to output the string as follow:

"--allow_html_in_templates=false --compress_colors=false..."

if i add the condition, how to do:

if the value is false,the key and value would not output in the string(just only output the ture key and the others)


Solution

  • Here's how I would do it:

    " ".join("%s=%s" % (k, v) for k, v in csstidy_opts.iteritems() if v is not False)
    

    Not sure what exactly you mean about only outputting the "ture key", but this won't output things that are set to False in your input dictionary.

    Edit:

    If you need to put the arguments into args, you can do something pretty similar:

    args = ["%s=%s" % (k, v) for k, v in csstidy_opts.iteritems() if v is not False]