Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Basically edit the spaces in between the output.

>Solution :

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 }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading