How to write the dictionary key in a batch of text using python?
<p>I would be grateful for any help. I have a dictionary which looks like this:</p>

<p>TEST_versions = {'D14 2015' : 'X1', 'D12   2014' : 'X2'}</p>

<p>I want the key from the dictionary to be placed in my text (which I am appending to a file) so I have written:</p>

<pre><code>for v in TEST_versions.keys():
    #print(v)
    add_code = open('make_all_ascii_files.txt','a')
    add_code.write("""
SELECT IF (Version_selector = v).""")
</code></pre>

<p>v is not taking the value of the key, rather the letter v is being appended to the file. How can I write the code so v takes the value 'D14 2015' for example.</p>

<p><em>v</em> is not replaced within string itself.
You can do something like following, for example (using named placeholders)</p>

<pre><code>for k in TEST_versions.keys():
    add_code = open('make_all_ascii_files.txt','a')
    add_code.write(
        "SELECT IF (Version_selector = %(value)s)."
        % { 'value': TEST_versions[k] }
    )
</code></pre>

<p>or </p>

<pre><code>for k in TEST_versions.keys():
    add_code = open('make_all_ascii_files.txt','a')
    add_code.write("""SELECT IF (Version_selector = %s).""" % TEST_versions[k] )
</code></pre>

<p>or</p>

<pre><code>for k, v in TEST_versions.items():
    add_code = open('make_all_ascii_files.txt','a')
    add_code.write("SELECT IF (Version_selector = %s)." % v)
</code></pre>

<p>or some other options for string formatting. Python got lots of options for this</p>

<p>I guess you'd like to review <a href="https://docs.python.org/2/library/string.html#format-string-syntax" rel="nofollow">https://docs.python.org/2/library/string.html#format-string-syntax</a> for details.</p>

python dictionary