Printing dict is not showing expected output

This is the dict data(headers) I am using for REST API get call.

column="name"
order="descending"
headers = {
            'accept': 'application/json',
            'orderby': '{"'+column+'":"'+order[:4]+'"}',
        }
print(headers)

This gives me following output:

{'accept': 'application/json','orderby': '{"\'name\'":"desc"}'}

I am getting 400- BAD Request because of this error in header.

I am expecting the following output that is without ‘(slash)’ in second key-value pair.

How to print this expected output?

{'accept': 'application/json','orderby': '{"name":"desc"}'}

>Solution :

Reading between the lines a bit, it looks like what you’re trying to generate for the orderby value is a JSON-encoded version of the dictionary {column: order[:4]}. Rather than try to build this yourself with string interpolation I strongly suggest using the built-in json module, which will handle all the formatting for you (including how to quote the string values, escape them appropriately, etc):

import json

column = "severity"
order = "descending"
headers = {
    'accept': 'application/json',
    'orderby': json.dumps({column: order[:4]})
}

print(headers)
{'accept': 'application/json', 'orderby': '{"severity": "desc"}'}

Leave a Reply