How to pretty-print cyclic dictionaries?

Robert Kern robert.kern at
Thu Apr 29 18:56:03 CEST 2010

On 4/29/10 11:23 AM, Dietrich Bollmann wrote:
> Hi,
> I would like to represent graphs as cyclic dictionaries in Python.
> The python code for the graphs is generated by some other program
> (written in lisp) and I wonder what would be the best syntax for writing
> the cycles in Python?

You can implement your ideas using Armin Ronacher's

The default pretty printer for dicts looks like this:

     def dict_pprinter(obj, p, cycle):
         if cycle:
             return p.text('{...}')
         p.begin_group(1, '{')
         keys = obj.keys()
         except Exception, e:
             # Sometimes the keys don't sort.
         for idx, key in enumerate(keys):
             if idx:
             p.text(': ')
         p.end_group(1, '}')

You could conceivably subclass RepresentationPrinter (the variable p above is an 
instance of this) that will assign increasing ID numbers to repeated objects so 
you can tag them.

Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco

More information about the Python-list mailing list