在python列表中打印字典值 [英] print dictionary values which are inside a list in python
问题描述
car_object = {} $ b $我想尝试打印出python中的列表中的dict值。 b cursor = self._db.execute('SELECT IDENT,MAKE,MODEL,DISPLACEMENT,POWER,LUXURY FROM CARS')
用于游标行:
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'],行['MAKE'],行['MODEL'],行['DISPLACEMENT'],行['POWER'],行['LUXURY'])
yield dict (行)
所以打印:
Car_Object_meA160 {'power':55,'ident':'meA160','model':'A160 CDI','disp':1.7,'make':'mercedes' '鲁'n'}
Car_Object_meA190 {'power':92,'ident':'meA190','model':'A190','disp':1.7,'make':'mercedes'豪华':'Y'}
Car_Object_meA210 {'power':103,'ident':'meA210','model':'A210 EVO','disp':1.7,'make':'mercedes' '奢侈':'Y'}
...等等
我想可以这样打印:
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
所以我想要能够打印的只是值....以标题排列一定的方式。有可能做到吗?谢谢。
棘手的部分是对齐几个表条目和表头。为此,我们首先要找出每列最长条目的长度。 pad
然后可以用于在给定的字符串中添加一些填充空格。
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])
现在,我们可以使用上面定义的 pad
函数在 car_objects
中打印头文件和几个条目。 / p>
print pad(,name)+.join(pad(f.upper(),f)for f在字段中)
名称,car in car_objects.items():
print pad(name,name)+.join(pad(car [f],f)for f in字段)
假设 car_objects
是Python字典。如果没有,请尝试用上述代码中的 getattr(c,f)
替换 car [f]
。 p>
更新:当然,如果您在实际打印之前知道所有行,则完全对齐表的列仅适用。如果您必须在数据库中读取条目时打印它们,那么您必须通过填充字符串的空格来猜测,以便它们在表格中很好地对齐。这使得所有的东西都更简单。只需将之前的这一行放在循环之前打印表头:
print(* 20)+.join(f.upper()。ljust(10)for f in fields)
在你的循环中的这一行,在收益
之前:
print name.ljust(20)+.join(str(getattr(car,f))。ljust(10)for f in fields)
/ pre>
str.ljust(n)
是一个标准字符串函数,返回与左侧对齐的字符串总宽度n
个字符。对齐右对齐和中心对齐有类似的功能:rjust
和center
。而且由于你的车似乎是一些类的实例,你可以使用内置函数getattr(< object>,< attribute name>)
来检索汽车(类似于您的getVariable
方法)。
有关字符串格式的更多信息,一个href =http://docs.python.org/3/tutorial/inputoutput.html#fancier-output-formatting =nofollow> Python文档页面。
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.
解决方案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 thepad
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 replacecar[f]
withgetattr(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 ofn
characters. There are similar functions for aligning right and center alignment:rjust
andcenter
. And since your cars seem to be instances of some class, you can use the builtin functiongetattr(<object>, <attribute name>)
to retrieve the individual attributes of the cars (similar to yourgetVariable
method).For more on string formatting, take a look a this Python documentation page.
这篇关于在python列表中打印字典值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!