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

115,101

Solution 1

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

Solution 2

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"}

Solution 3

# 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"}

Solution 4

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"}

Solution 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.

Share:
115,101

Related videos on Youtube

Shankar
Author by

Shankar

Senior Data Scientist @LexisNexis | Pythonista

Updated on October 17, 2020

Comments

  • Shankar
    Shankar over 3 years

    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.

    • qaphla
      qaphla almost 11 years
      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).
    • Russell Borogove
      Russell Borogove almost 11 years
      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.
    • Shankar
      Shankar almost 11 years
      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.
    • Russell Borogove
      Russell Borogove almost 11 years
      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.
    • abarnert
      abarnert almost 11 years
      @RussellBorogove: Or, more fundamentally, confused about the difference between an actual string object and its representation.
    • Jon-Eric
      Jon-Eric almost 11 years
      @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?
    • Lennart Regebro
      Lennart Regebro almost 11 years
      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.
    • Raymond Hettinger
      Raymond Hettinger about 9 years
      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.
    • Robino
      Robino about 6 years
      @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)
  • Shankar
    Shankar almost 11 years
    Solution is fine for printing. What if I need to further update or iterate the dictionary after quote alteration?
  • Shankar
    Shankar almost 11 years
    I am looking for an alternate option where I can force the double quotes as the default option for Python dictionaries.
  • Brent Washburne
    Brent Washburne almost 11 years
    Update the pairs and then execute this line again.
  • Pranjal Mittal
    Pranjal Mittal over 10 years
    @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?
  • akhomenko
    akhomenko over 7 years
    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.
  • penny chan
    penny chan over 6 years
    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
  • Sidon
    Sidon almost 6 years
    This is the answer that should be accepted as correct.
  • Oldboy
    Oldboy about 5 years
    @Sidon I second that.
  • David Beauchemin
    David Beauchemin almost 3 years
    And if you use UTF-8 you need to ensure_ascii=False