print dictionary values which are inside a list in python

2024/11/15 17:41:00

I am trying to print out just the dict values inside a list in python.

car_object = {}cursor = self._db.execute('SELECT IDENT, MAKE, MODEL, DISPLACEMENT, POWER, LUXURY FROM CARS')for row in cursor:objectname = 'Car_Object_'+str(row['IDENT'])# print (objectname)car_object[objectname] = Cars(ident = row['IDENT'], make = row['MAKE'], model = row['MODEL'], disp = row['DISPLACEMENT'], power = row['POWER'], luxury = row['LUXURY'])print(objectname, car_object[objectname])#print(row['IDENT'], row['MAKE'], row['MODEL'], row['DISPLACEMENT'], row['POWER'], row['LUXURY'])yield dict(row)

So it is printing:

Car_Object_meA160 {'power': 55, 'ident': 'meA160', 'model': 'A160 CDI', 'disp': 1.7, 'make': 'mercedes', 'luxury': 'N'}
Car_Object_meA190 {'power': 92, 'ident': 'meA190', 'model': 'A190', 'disp': 1.7, 'make': 'mercedes', 'luxury': 'Y'}
Car_Object_meA210 {'power': 103, 'ident': 'meA210', 'model': 'A210 EVO', 'disp': 1.7, 'make': 'mercedes', 'luxury': 'Y'}

...and so on I want to be able to print it like so:

                      IDENT         MAKE         MODEL        DISP       POWER     LUX
Car_Object_meA160     meA160       mercedes      A160 CDI     1.7          55      N
Car_Object_meA190     meA190       mercedes      A190         1.7          92      Y
Car_Object_meA210     meA210       mercedes      A210 EVO     1.7          103     Y

So i want to be able to print just the values....with the headers ordered a certain way. Is it possible to do this? Thanks.

Answer

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.

https://en.xdnf.cn/q/120425.html

Related Q&A

Triangle of numbers on Python

Im asked to write a loop system that prints the following:0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 0 1 2 3 4 5 0 1 2 3 4 0 1 2 3 0 1 2 0 1 0However, my script prints this:0 1…

Using regex to ignore invalid syntax [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

What is the requirements.txt file? What should be in it in this particular case?

I am switching from Replit to PebbleHost to host my Python bot. What do I put in my requirements.txt file? These are the imports that I have at the start of my bot. import asyncio import datetime impo…

Is this a linux or a virtualenv error?

I asked this question 4 days ago.Now, when I open a terminal, I see this:and this:Is it related to the initial problem i had, or it a python and virtualenv issue?

Python code to authenticate to website, navigate through links and download files

Im looking something which could be interesting to you as well. Im developing a feature using Python, which should be able to authenticate (using userid/password and/or with other preferred authentica…

How to get sum of products of all combinations in an array in Python? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

How to get value from entry (Tkinter), use it in formula and print the result it in label

When using the function entry of Tkinter, you can write a string value and do things with it; but Im actually working with formulas. The idea is fairly simple: to put a bunch of boxes to fill with numb…

Printing tuples in a list

Im not getting how to proceed with this problem in lists,can any one help me out? Thanks in advance.input is :l = [(1,2),(3,4),(5,6)]output is:[(1,3,5),(2,4,6)]

Adding entries from multiple files in python

I have a question on how to add entries from 100 files (each file contains two columns) and then writing them to a new file(which will also contain two columns)?

Multiply list in list string items with list in list integers

I have 2 lists: list1 and list2 list1 is a list in list and contains various strings list2 is also a list in list and consists of different integer values the dimensions of both lists is the same how d…