简体   繁体   English

Python-从dict行打印

[英]Python - Printing in line from dict

I'm a beginner at python and I'm experiencing difficulties printing nicely. 我是python的初学者,我在打印时遇到困难。 I made a program that stores names and prices in dictionary. 我编写了一个程序,在字典中存储名称和价格。 ( eg : {"PERSON_1":"50","PERSON_2":"75","PERSON_WITH_EXTREMELY_LONG_NAME":"80"} Now the problem is that I want to be able to print the keys and their supposed values in a nice scheme. I used the code: (例如: {"PERSON_1":"50","PERSON_2":"75","PERSON_WITH_EXTREMELY_LONG_NAME":"80"}现在的问题是我希望能够以一种很好的方式打印键及其假定值我使用了代码:

 for i in eter.eters:
        print(i + "\t | \t" + str(eter.eters[i]))

with eter.eters being my dictionary. eter.eters是我的字典。 The problem is that some names are a lot longer than others, so the tabs don't align. 问题在于某些名称比其他名称长很多,因此选项卡不对齐。 As well as my header: "Names" | 以及我的标题:“名称” | "Price" should be aligned with the information below. “价格”应与以下信息保持一致。 I've already looked up some solutions, but I don't really understand the ones I found. 我已经找到了一些解决方案,但是我不太了解我找到的解决方案。 Desired outcome: 期望的结果:

**********************************************************************
               De mensen die blijven eten zijn:
**********************************************************************
Naam                            |      bedrag
----------------------------------------------------------------------
PERSON 1                        |      50
PERSON 2                        |      75
PERSON WITH EXTREMELY LONG NAME |      80
**********************************************************************

try this: 尝试这个:

given eter.eters is your dictionary 给定eter.eters是你的字典

print('%-35s | %6s' % ('Names', 'Price')) # align to the left

for k in eter:
    print('%-35s | %6s' % (k,eter[k]))

or 要么

print("{0:<35}".format('Name')+'|'+"{0:>6}".format('Price'))

for k in eter:
    print("{0:<35}".format(k)+'|'+"{0:>6}".format(eter.eters[k]))

You can try to get all of the names and find the maximum length of it. 您可以尝试获取所有名称并找到其最大长度。 Then show every name with special padding instead of tabulator ( \\t ). 然后使用特殊填充而不是制表符( \\t )显示每个名称。 This code should explain: 该代码应说明:

>>> d={"Marius":"50","John":"75"}
>>> d
{'Marius': '50', 'John': '75'}
>>> for i in d:
...  print(i)
... 
Marius
John
>>> d = {"Marius":"50","John":"75"}
>>> m = 0
>>> for i in d:
...  m = max(m, len(i))
... 
>>> m
6 # now we know the place reserved for Name column should be 6 chars width
>>> for i in d:
...  print( i + (m-len(i))*' ' , d[i]) # so add to the name space char that fit this 6 chars space
... 
Marius 50
John   75

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM