Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Python dictionary with double quotes as default quote format?

I am trying to create a python dictionary which is to be used as a java script var inside a html file for visualization purposes. As a requisite, I am in need of creating the dictionary with all names inside double quotes instead of default single quotes which Python uses. Is there an easy and elegant way to achieve this.

    couples = [                ['jack', 'ilena'],                 ['arun', 'maya'],                 ['hari', 'aradhana'],                 ['bill', 'samantha']]     pairs = dict(couples)     print pairs 

Generated Output:

{'arun': 'maya', 'bill': 'samantha', 'jack': 'ilena', 'hari': 'aradhana'} 

Expected Output:

{"arun": "maya", "bill": "samantha", "jack": "ilena", "hari": "aradhana"} 

I know, json.dumps(pairs) does the job, but the dictionary as a whole is converted into a string which isn't what I am expecting.

P.S.: Is there an alternate way to do this with using json, since I am dealing with nested dictionaries.

like image 883
Shankar Avatar asked Aug 16 '13 23:08

Shankar


People also ask

Can we use double quotes in dictionary Python?

Generally, double quotes are used for string representation and single quotes are used for regular expressions, dict keys or SQL. Hence both single quote and double quotes depict string in python but it's sometimes our need to use one type over the other.

How do you keep double quotes in Python?

Quotes in strings are handled differently There is no problem if you write \" for double quotes " . In a string enclosed in double quotes " , single quotes ' can be used as is, but double quotes " must be escaped with a backslash and written as \" .

How do you insert a double quote into a quoted string?

If you need to use the double quote inside the string, you can use the backslash character. Notice how the backslash in the second line is used to escape the double quote characters. And the single quote can be used without a backslash.


1 Answers

json.dumps() is what you want here, if you use print json.dumps(pairs) you will get your expected output:

>>> pairs = {'arun': 'maya', 'bill': 'samantha', 'jack': 'ilena', 'hari': 'aradhana'} >>> print pairs {'arun': 'maya', 'bill': 'samantha', 'jack': 'ilena', 'hari': 'aradhana'} >>> import json >>> print json.dumps(pairs) {"arun": "maya", "bill": "samantha", "jack": "ilena", "hari": "aradhana"} 
like image 174
Andrew Clark Avatar answered Sep 23 '22 13:09

Andrew Clark