pprint(): how to use double quotes to display strings?
Asked Answered
A

3

29

If I print a dictionary using pprint, it always wraps strings around single quotes ('):

>>> from pprint import pprint
>>> pprint({'AAA': 1, 'BBB': 2, 'CCC': 3})
{'AAA': 1, 'BBB': 2, 'CCC': 3}

Is there any way to tell pprint to use double quotes (") instead? I would like to have the following behaviour:

>>> from pprint import pprint
>>> pprint({'AAA': 1, 'BBB': 2, 'CCC': 3})
{"AAA": 1, "BBB": 2, "CCC": 3}
Alienor answered 18/4, 2013 at 15:54 Comment(3)
Why do you need double quotes? pprint() just uses the repr() result of the strings, which will use ' unless a literal ' quote is contained.Roadability
Perhaps you are looking for json.dumps() instead? JSON uses double quotes for strings...Roadability
Thanks @Martijn, json.dumps() does what I need. Can you post it as an answer?Alienor
R
46

It looks like you are trying to produce JSON; if so, use the json module:

>>> import json
>>> print json.dumps({'AAA': 1, 'BBB': 2, 'CCC': 3})
{"AAA": 1, "BBB": 2, "CCC": 3}

The pprint() function produces Python representations, not JSON and quoting styles are not configurable. Don’t confuse the two syntaxes. JSON may at first glance look a lot like Python but there are more differences than just quoting styles:

  • JSON is limited to a few specific types only ({...} objects with key-value pairs, [...] arrays, "..." strings, numbers, booleans and nulls). Python data structures are far richer.
  • Python dictionary keys can be any hashable object, JSON object keys can only ever be strings.
  • JSON booleans are written in lowercase,true and false. Python uses title-case, True and False.
  • JSON uses null to signal the absence of a value, Python uses None.
  • JSON strings use UTF-16 codepoints, any non-BMP codepoint is encoded using surrogate pairs. Apart from a handful of single-letter backslash escapes such as \n and \" arbitrary codepoint escapes use \uXXXX 16-bit hexadecimal notation. Python 3 strings cover all of Unicode, and the syntax supports \xXX, \uXXXX, and \UXXXXXXXX 8, 16 and 32-bit escape sequences.

If you want to produce indented JSON output (a bit like pprint() outputs indented Python syntax for lists and dictionaries), then add indent=4 and sort_keys=True to the json.dumps() call:

>>> print json.dumps({'AAA': 1, 'CCC': 2, 'BBB': 3}, indent=4, sort_keys=True)
{
    "AAA": 1,
    "BBB": 2,
    "CCC": 3
}

See https://mcmap.net/q/45032/-how-to-prettyprint-a-json-file

Roadability answered 18/4, 2013 at 16:1 Comment(7)
This fixes the single->double quotes, but this is insufficient for manual viewing because it doesn't prettyprint the output.Lack
@Lack the point was that the OP was trying to produce JSON, and was using the wrong tool. They were not actually trying to pretty print! That said, the json.dumps() function can be configured to pretty print, up to a point.Roadability
I understand. I'm facing the same issue, but I need both-- I need to read the output json manually, and plug it into something that takes .json format. I just wanted to include the information I found-- that this does indeed switch the single to double quotes, but doesn't pretty print it.Lack
For pretty printed JSON see #12944319. Again, that was never the point of this answer.Roadability
Check. it was clear from my initial comment that you answered the original question. To wrap this up, I think this answer #12944319 uses your solution with an indent parameter that helps with viewing.Lack
@MartijnPieters, Are you aware of any performance implications of using - pprint.pformat() Vs - json.dumps() while printing a large JSON. json.dumps() is expensive?Crackling
@SubhakarKS: pprint is pure-python code intended as a developer tool, while the json module uses a C extension to improve its performance. pprint tools also output Python syntax, not JSON, you can't compare the two.Roadability
C
1

While I'm against using modules for simple things, but over the time pprint is becoming useless and not catching up with the Python 3 evolution. At least they could have added this option as a parameter.

So take advantage of the black module that prints your objects in pretty format already.

Here is the code,

import black
print(black.format_file_contents(str(D), fast=False, mode=black.FileMode()))

Will print

 '{"AAA": 1, "BBB": 2, "CCC": 3}'
Chlorohydrin answered 2/10, 2022 at 10:35 Comment(0)
D
0

I see that the OP wanted JSON, but I do not want JSON and pprint is so close to giving me what I do want: black-compatible Python source, which requires that I use " instead of '.

I settled on .replace("'", '"') with pformat(), although this is both ugly and fragile ☹️:

import pprint

# Note: my code auto-generates my_dict parsing a file (not black-formatted here)
my_dict = ["spam", "eggs", "lumberjack", "knights", "ni", "eggs", "lumberjack", "knights", "ni"]

pprinter = pprint.PrettyPrinter(indent=4)
formatted_code = (
    pprinter.pformat(my_dict)
    .replace("[ ", "[\n  ")  # break after opening bracket
    .replace("']", "',\n]")  # break before closing bracket, add comma
    .replace("'", '"')  # use double quotes
)
with open("example_module.py", "w", encoding="utf-8") as outfile:
    outfile.write('"""Module containing auto-generated ALL_MR_HEADERS."""\n')
    outfile.write(f"ALL_MR_HEADERS = {formatted_code}\n")

The resulting example_module.py is black-compliant.

Donelladonelle answered 9/9, 2022 at 20:49 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.