-1
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)

Terry
  • 127
  • 1
  • 11
  • 1
    the last 4 lines of code you have there seem to be the solution already: you can simply take a string `csstidy=""` and add all map items as you proposed: `csstidy += "--"+key+"="+value+" "` under the condition that value equals `True` – devsnd Mar 16 '12 at 15:31

2 Answers2

4

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]
xitrium
  • 4,235
  • 4
  • 23
  • 17
0

You could do something like this:

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,  
}

a = ""
for key,value in csstidy_opts.iteritems():    
    if value != False:
        a+=key+'='+str(value)+' '
 print a

output is

--merge_selectors=2

also note false need to be False

malbani
  • 136
  • 4
  • 1
    Multiple levels of string concatenation is not a recommended or efficient approach. Use the list comprension and string formatting from the other answer – jdi Mar 16 '12 at 15:56
  • @malbani,if i use `args = []`, how to so,and use `append` to push the key and the value into the array! i am a beginner for python,but i want to coding the csstidy package for sublime Text 2!! – Terry Mar 16 '12 at 16:03
  • @jdi wow never realized python string concatenation was so much slower then .join. Here is a comparison i found after reading your comment [link](http://stackoverflow.com/questions/3055477/how-slow-is-pythons-string-concatenation-vs-str-join) – malbani Mar 16 '12 at 17:43