The tricky part is aligning the several table entries and the table headers. For this, we first have to find out how long the longest entry in each column is. pad
then can be used to add a number of padding spaces to the given string.
fields = ["ident", "make", "model", "disp", "power", "luxury"]
max_len = {"name": max(map(len, car_objects)) + 1}
for f in fields:
max_len[f] = max(map(len, [f] + [str(car[f]) for car in car_objects.values()]))
pad = lambda s, f: str(s).ljust(max_len[f])
Now, we can print the headers and the several entries in car_objects
using the pad
function defined above.
print pad("", "name") + " ".join(pad(f.upper(), f) for f in fields)
for name, car in car_objects.items():
print pad(name, "name") + " ".join(pad(car[f], f) for f in fields)
This should work, assuming that the elements of car_objects
are Python dictionaries. If not, try to replace car[f]
with getattr(c, f)
in the above code.
Update: Of course, perfectly aligning the columns of the table only works if you know all the rows before actually printing them. If you have to print them while still reading entries from the database, you have to ‘guess’ by how many spaces to pad the strings so they are nicely aligned in a table. This makes everything much simpler. Just put this line before your for
loop for printing the table headers:
print (" " * 20) + " ".join(f.upper().ljust(10) for f in fields)
And this line inside your loop, before the yield
:
print name.ljust(20) + " ".join(str(getattr(car, f)).ljust(10) for f in fields)
str.ljust(n)
is a standard string function that return the string aligned to the left within a total width of n
characters. There are similar functions for aligning right and center alignment: rjust
and center
. And since your cars seem to be instances of some class, you can use the builtin function getattr(<object>, <attribute name>)
to retrieve the individual attributes of the cars (similar to your getVariable
method).
For more on string formatting, take a look a this Python documentation page.
2
solved print dictionary values which are inside a list in python