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>You need to <a href="https://docs.python.org/2/library/stdtypes.html#str.format" rel="nofollow">format</a> the string with the variable:</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 = {}).""".format(v))
</code></pre>

<p>If you have more than one variable you're formatting you can index them:</p>

<pre><code>for v in TEST_versions:
    #print(v)
    add_code = open('make_all_ascii_files.txt','a')
    add_code.write("""
SELECT IF (Version_selector = {0}; value={1}).""".format(v, TEST_versions[v]))
</code></pre>

<p>Note that the call to <code>.keys()</code> is unnecessary in your example because python iterates over a dictionary's keys by default.</p>

python dictionary