Convert single quotes to double quotes for Dictionary key/value pair
<p>I have a dictionory with key value pair in single inverted commas as follows:</p>

<pre><code>filename = 'sub-310621_task-EMOTION_acq-LR_bold.nii.gz'
intended_for ={"IntendedFor", filename}
</code></pre>

<p>AS i am want to write this dictionary to a json file i have to have filename in between two inverted commas eg: <code>"sub-310621_task-EMOTION_acq-LR_bold.nii.gz"</code></p>

<p>SO the output should look like:</p>

<pre><code>intended_for ={"IntendedFor", "sub-310621_task-EMOTION_acq-LR_bold.nii.gz"}
</code></pre>

<p>This output will be written in to test.json file which should look like:</p>

<pre><code>{
    "IntendedFor": "sub-310621_task-EMOTION_acq-LR_bold.nii.gz"
}
</code></pre>

<p>How can i do this in python ?</p>

<p>Rather than trying to build the JSON string yourself you should use the <a href="https://docs.python.org/3.5/library/json.html" rel="nofollow">json</a> module to do the encoding.</p>

<p>The <code>json.dumps()</code> method takes an object such as a dictionary with key value pairs and converts it into a JSON compliant string which can then be written to a file.</p>

<p>Instead of a dictionary, you created a set by using a comma <code>,</code> instead of a colon <code>:</code></p>

<pre><code>intended_for = {"IntendedFor", filename}
</code></pre>

<p>The correct code for your input would be</p>

<pre><code>filename = 'sub-310621_task-EMOTION_acq-LR_bold.nii.gz'
intended_for ={"IntendedFor": filename}
</code></pre>

<p>Then you can encode</p>

<pre><code>import json
json_string = json.dumps(intended_for)
</code></pre>

python json dictionary