Kashi Vishwa Kashi Vishwa - 1 month ago 9
Python Question

Convert single quotes to double quotes for Dictionary key/value pair

I have a dictionory with key value pair in single inverted commas as follows:

filename = 'sub-310621_task-EMOTION_acq-LR_bold.nii.gz'
intended_for ={"IntendedFor", filename}

AS i am want to write this dictionary to a json file i have to have filename in between two inverted commas eg:

SO the output should look like:

intended_for ={"IntendedFor", "sub-310621_task-EMOTION_acq-LR_bold.nii.gz"}

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

"IntendedFor": "sub-310621_task-EMOTION_acq-LR_bold.nii.gz"

How can i do this in python ?


Rather than trying to build the JSON string yourself you should use the json module to do the encoding.

The json.dumps() 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.

Instead of a dictionary, you created a set by using a comma , instead of a colon :

intended_for = {"IntendedFor", filename}

The correct code for your input would be

filename = 'sub-310621_task-EMOTION_acq-LR_bold.nii.gz'
intended_for ={"IntendedFor": filename}

Then you can encode

import json
json_string = json.dumps(intended_for)