Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"}'}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading