120

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.

Shankar
  • 3,496
  • 6
  • 25
  • 40
  • Not that it solves your problem, but a better way to create pairs would be to replace your lines 2-4 with pairs = dict(couples). – qaphla Aug 17 '13 at 00:01
  • 6
    When you ask to print a dictionary, you're printing the conversion of the dictionary to a string anyway, so JSON is completely appropriate -- particularly if you're trying to interchange with Javascript. – Russell Borogove Aug 17 '13 at 00:02
  • I need an alternate method, since I am in need of updating and iterating through the dictionary after the double quote alteration. json.dumps converts the dict to string. Is there a way to make double quotes the default option. – Shankar Aug 17 '13 at 00:17
  • 9
    You're not altering anything about the dictionary. You're creating a string representation of it. The dictionary doesn't contain single quotes. It contains strings. You are confused about what a dictionary is. – Russell Borogove Aug 17 '13 at 00:24
  • 1
    @RussellBorogove: Or, more fundamentally, confused about the difference between an actual string object and its representation. – abarnert Aug 17 '13 at 00:34
  • 1
    @ArunprasathShankar You need to explain *why* you think making double quotes the default is your only option. Converting to JSON doesn't preclude more updates. You can always convert to JSON again if there are more updates, right? – Jon-Eric Aug 17 '13 at 01:12
  • Dictionaries do not have double quotes as default in Python, because **strings** doesn't have double quotes by default in Python. There is a reason for that, so what you are asking for doesn't really make sense. Please, therefore explain **why** you want this. – Lennart Regebro Aug 17 '13 at 05:43
  • 2
    The question seems fundamentally misguided. The "print" keyword calls \_\_str\_\_ on the dictionary and converts is to a string just like ``json.dumps(pairs)`` does. The OP shows a basic misunderstanding he/she saids "but the dictionary as a whole is converted into a string which isn't what I am expecting." In fact, when you print an object, regardless of how you print it, the object is first converted to a string. – Raymond Hettinger Jun 12 '15 at 15:44
  • @RaymondHettinger is right - the question is based on the assumption that there are single-quote strings and double-quote strings in python. What the OP really wants is to be able to have the string quoted using double quotes when it is printed out to build some javascript. For this the correct answer is simply `javascript_output += "my_js_var = " + json.dumps(my_python_dict)` – Robino Jun 12 '18 at 11:46

7 Answers7

103

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"}
mirekphd
  • 4,799
  • 3
  • 38
  • 59
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
  • 2
    I am looking for an alternate option where I can force the double quotes as the default option for Python dictionaries. – Shankar Aug 17 '13 at 00:18
  • 1
    @FJ: In the second case json.dumps(pairs) is returning a string. What if I want a `dict` type object output in which the string keys are in double quotes? – Pranjal Mittal Mar 01 '14 at 17:53
  • 8
    `json.dumps` will convert the dictionary to string, eventhough it looks good with double quotes, `type(json.dumps(pairs))` is string, I don't think this is what OP expect – penny chan Jan 13 '18 at 01:24
  • It return a string. Not a dictionary. The answer seems misleading. – Professor Jan 21 '23 at 11:47
75

You can construct your own version of a dict with special printing using json.dumps():

>>> import json
>>> class mydict(dict):
        def __str__(self):
            return json.dumps(self)

>>> couples = [['jack', 'ilena'], 
               ['arun', 'maya'], 
               ['hari', 'aradhana'], 
               ['bill', 'samantha']]    

>>> pairs =  mydict(couples) 
>>> print pairs
{"arun": "maya", "bill": "samantha", "jack": "ilena", "hari": "aradhana"}

You can also iterate:

>>> for el in pairs:
       print el

arun
bill
jack
hari
elyase
  • 39,479
  • 12
  • 112
  • 119
  • 7
    This doesn't work if some of your dict values are bools and you plan to use the resulting string in some other context where it would be evaluated as Python code. – akhomenko Feb 21 '17 at 23:47
  • 2
    And if you use UTF-8 you need to `ensure_ascii=False` – David Beauchemin Jun 29 '21 at 21:26
  • If you don't want the `json.dumps` to escape the backward slash or unicode but keep the format as the same before dumping, you'll need to pass the argument `ensure_ascii=False` to json.dumps as David said above. – Jason Liu Sep 28 '22 at 21:05
13
# do not use this until you understand it
import json

class doubleQuoteDict(dict):
    def __str__(self):
        return json.dumps(self)

    def __repr__(self):
        return json.dumps(self)

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

Yields:

{"arun": "maya", "bill": "samantha", "jack": "ilena", "hari": "aradhana"}
Russell Borogove
  • 18,516
  • 4
  • 43
  • 50
8

Here's a basic print version:

>>> print '{%s}' % ', '.join(['"%s": "%s"' % (k, v) for k, v in pairs.items()])
{"arun": "maya", "bill": "samantha", "jack": "ilena", "hari": "aradhana"}
Brent Washburne
  • 12,904
  • 4
  • 60
  • 82
5

The premise of the question is wrong:

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.

You should be expecting a conversion to a string. All "print" does is convert an object to a string and send it to standard output.

When Python sees:

print somedict

What it really does is:

sys.stdout.write(somedict.__str__())
sys.stdout.write('\n')

As you can see, the dict is always converted to a string (afterall a string is the only datatype you can send to a file such as stdout).

Controlling the conversion to a string can be done either by defining __str__ for an object (as the other respondents have done) or by calling a pretty printing function such as json.dumps(). Although both ways have the same effect of creating a string to be printed, the latter technique has many advantages (you don't have to create a new object, it recursively applies to nested data, it is standard, it is written in C for speed, and it is already well tested).

The postscript still misses the point:

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

Why work so hard to avoid the json module? Pretty much any solution to the problem of printing nested dictionaries with double quotes will re-invent what json.dumps() already does.

Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
2

The problem that has gotten me multiple times is when loading a json file.

import json
with open('json_test.json', 'r') as f:
    data = json.load(f)
    print(type(data), data)
    json_string = json.dumps(data)
    print(json_string)

I accidentally pass data to some function that wants a json string and I get the error that single quote is not valid json. I recheck the input json file and see the double quotes and then scratch my head for a minute.

The problem is that data is a dict not a string, but when Python converts it for you it is NOT valid json.

<class 'dict'> {'bill': 'samantha', 'jack': 'ilena', 'hari': 'aradhana', 'arun': 'maya'}
{"bill": "samantha", "jack": "ilena", "hari": "aradhana", "arun": "maya"}

If the json is valid and the dict does not need processing before conversion to string, just load as string does the trick.

with open('json_test.json', 'r') as f:
    json_string = f.read()
    print(json_string)
shao.lo
  • 4,387
  • 2
  • 33
  • 47
2

It's Easy just 2 steps

step1:converting your dict to list

step2:iterate your list and convert as json .

For better understanding check down below snippet

import json
couples = [
               ['jack', 'ilena'], 
               ['arun', 'maya'], 
               ['hari', 'aradhana'], 
               ['bill', 'samantha']]
pairs = [dict(couples)]#converting your dict to list
print(pairs)

#iterate ur list and convert as json
for x in pairs:
    print("\n after converting: \n\t",json.dumps(x))#json like structure