Home > Mobile >  Print dictionary pretty way in Python
Print dictionary pretty way in Python

Time:05-12

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

CodePudding user response:

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
  • Related