Home > Back-end >  Print correct tabspaces with dictionaries in VScode Jupyter Notebooks
Print correct tabspaces with dictionaries in VScode Jupyter Notebooks

Time:02-15

Is there a way to print a python dictionary in VScode Jupyter Notebooks in the following style

foo:                       0
bar:                       1
foobar:                    99
long_word:                 photosynthesis
n_coeffs:                  6

regardless of the size of the key?

Trying this

dict = {"foo": 0, "bar": 1, "foobar": 99, "long_word": "photosynthesis", "n_coeffs": 6}

for key, value in dict.items():
    print('{:<20}{:<20}'.format(key,value)) # code by Tal Folkman, see answers

results in the vscode builtin notebook output renderer as

foo:                        0
bar:                        1
foobar:                     99
long_word:                  photosynthesis
n_coeffs:               6

Or other variants of mis-alignements. When copy-pasting the output to an editor, the spaces are correct, but the renderer does not conform to that. Is there a way to configure the builtin renderer to display all spaces?

CodePudding user response:

I think what's happening here is that it's taking the space after the end of the last character of key hence unequal spaces

CodePudding user response:

You can use a format string to set the columns to a minimum of 30 characters and align text to left:

for key, value in dict.items():
   print("{: <30} {: <30} ".format(*[key,value ]))

Example from my python notebook I have just tested

CodePudding user response:

in order to use indentation you can use print('{:<20}{:<20}'.format()):

dict = {"foo": 0, "bar": 1, "foobar": 99, "long_word": "photosynthesis", "n_coeffs": 6}

for key, value in dict.items():
    print('{:<20}{:<20}'.format(key,value))

#output:

foo                 0                   
bar                 1                   
foobar              99                  
long_word           photosynthesis      
n_coeffs            6    

CodePudding user response:

dict = {"foo": 0, "bar": 1, "foobar": 99, "long_word": "photosynthesis", "n_coeffs": 6}

n=max([int(len(key)/4) for key, value in dict.items()])
for key, value in dict.items():
    k=int(len(key)/4)
    print(key '\t' (n-k)*'\t' str(value))

if you want colon additionally use like below,

dict = {"foo": 0, "bar1": 1, "foobar": 99, "long_word": "photosynthesis", "n_coeffs": 6}
n=max([int(len(key ':')/4) for key, value in dict.items()])
for key, value in dict.items():
    print(key ':' '\t' (n-int(len(key ':')/4))*'\t' str(value))
  • Related