Search code examples
pythondictionaryprintingellipsis

What does `{...}` mean in a python 2 dictionary value printed?


While debugging a python program I had to print the value of a huge dictionary on a log file. I copy-pasted the value and when I assigned it in the python 2 interpreter I got SyntaxError: invalid syntax. What? How was that possible? After a closer look I realised the dictionary in the file was something like this:

{'one': 1, 'two': 2, 'three': {...}}

The key three value was {...}, which caused the invalid syntax error.

Pasting this dictionary on a python 2 interpreter raises a Syntax Error exception. Pasting it on a python 3 interpreter the assigned value results to be {'one': 1, 'two': 2, 'three': {Ellipsis}}.

So, what does {...} mean in python 2 and why the syntax is invalid in python 2 even if the value is printed in the log file from a python 2 script?


Solution

  • If you write a dictionary like this:

    d = dict(one=1, two=2)
    d['three'] = d
    print(d)
    

    you get the output

    {'one': 1, 'two': 2, 'three': {...}}
    

    (though order may vary on older versions of Python).

    ... in container repr are used to indicate that a container contains itself, so that the repr doesn't become infinitely recursive.