Printing out dictionary without whitespaces

I am doing some exercises but I am not able to complete due to some formatting I am supposed to follow when printing the dictionary.

a_dict = {
          'apple': 1,
          'orange': 2
          }

Output

{'apple': 1, 'orange': 2}

Is there any way I can format it to be like this?

{ 'apple':1, 'orange':2 }

Basically edit the spaces in between the output.


Solution 1:

You can't modify the __repr__ method of built-ins such as dict but you can print it as you wish. For example:

>>> a = {'apple': 1, 'orange': 2}
>>> print("{{ {} }}".format(", ".join(f"{repr(k)}:{repr(v)}" for k, v in a.items())))
{ 'apple':1, 'orange':2 }