-1

I would like to output dict data in the form of a table in the console:

dtc={ "test_case1_short":{"test_step11":"pass","test_step12":"pass","test_step_13":{"status":"failed","details":"ca marche po"}, "test_case2_longest_name":{"test_step21":"ne","test_step22":"ne"}, "test_case3_medium_name":{"test_step31":"ne","test_step32":"ne"} }

note: for french speakers 'dtc' is a shortcut for dict_test_collection (!)

To build this table I would like to determine the size of key names in order to dimension my column headers. I can get my key names max length doing this:

max = 0
for i in list(dtc.keys()):
if max < len(i):
    max = len(i)
print(max)

but I find this not very straighforward ... is there a way to get this information from dict.keys() or another dict feature ?

Besides, I'd like to set separators like "+-----------------------------+" for section headers and "| |" for section bodies, to have a good looking table. In section bodies, is there a straight and simple way to set the table and columns width (ie. '|' caracter ending up at column 50, whatever the text on the line, like padding the line with spaces until a certain column)

Thank you

Alexandre

A.Joly
  • 2,317
  • 2
  • 20
  • 25

1 Answers1

0

is there a way to get this information from dict.keys() or another dict feature ?

This seems straightforward to me:

max_key_len = max(len(key) for key in dtc)
print(max_key_len)

This one seems less straightforward, but it is shorter:

max_key_len = max(map(len, dtc))
print(max_key_len)
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • thanks for your reply, but I have a TypeError: 'int' object is not callable. If I do [len(key) for key in dtc] I can get length values but I cannot apply max() on it ... – A.Joly Jul 25 '17 at 15:35
  • 1
    You've redefined the `max` function somewhere previously in your code. Try not to name your variables after built-in functions. Or, `import builtins` and then use `builtins.max(len(key) for key in dtc)`. – Robᵩ Jul 25 '17 at 15:43