-2

Is there a way to print the contents of a dictionary without have to iterate over the dictionary? In javascript you can console.log to view the contents of the object. Is there something similar in python?

I've tried print statement as well as object.keys() and object.values(). However, I would like to see the entire dictionary via print statement.

print(dictionary)

I expect {a: 1} instead of object at 0x7efd79610278>

Chris Smith
  • 399
  • 3
  • 16

1 Answers1

0

I don't think the variable dictionary is what you think it is. Here's a small example in the Python3 REPL (Read. Evaluate. Print. Loop) that shows the printing a dictionary with the expected behavior.

$ python3
Python 3.7.3 (default, Apr  3 2019, 05:39:12) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a = {}
>>> a[0] = '0'
>>> a
{0: '0'}
>>> print(a)
{0: '0'}

To answer your question the default __str__ method pronounced (dunder str) should be sufficient. However if it is not you could do something the following and provide your own implementation.

>>> import json
>>> class MyDict(dict):
...     def __str__(self):
...             return json.dumps(self)
... 
>>> d = MyDict()
>>> d['key'] = 'value'
>>> print(d)
{"key": "value"}
Skam
  • 7,298
  • 4
  • 22
  • 31