'Print dictionary pretty way in Python
Is there any way to print a dictionary from a class in a pretty way?
I have a dictionary and when I print de class I want to return it with its keys and its values, like this:
key1: value1
key2: value2
...
I can't find a way to return it this way.
Here is where I want to put the code
def __str__(self):
for key in self.__dicc:
d = str(self.__dicc.get(key))
return d
Solution 1:[1]
You can loop through a dictionary key-value pairs using items method
def __str__(self):
d = ""
for k, v in self.__dicc.items():
d += f"{k}: {v}\n"
return d
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | monk |
