循环浏览字典并以某种形式打印出来

2024-05-17 07:33:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下字典:

# a small DB of people who stole my books

dic = {
'Cohen'     : 'Calvino' 'Evertt' 'Borges',
'Larry'     : 'The Bible', 
'Volanski'  : 'Phone Book'
}

# here's an abortive attempt to print it in a CSV format
for k in dic.keys():
    print (k, '\t')
for v in dic.keys():
    print (dic[v], ' ')

这就是难看的输出:

^{pr2}$

这就是我希望输出的样子:

Cohen      Larry       Volanski  
Calvino    The Bible   Phone Book  
Evertt  
Borgest  

(只有制表符分开,我没能在这里显示)


Tags: theinfor字典phonekeysbibleprint
3条回答
dic = {
   'Cohen'     : ['Calvino', 'Evertt', 'Borges'],
   'Larry'     : ['The Bible'],
   'Volanski'  : ['Phone Book']
}


ordered = []
maxlen = 0

for k in sorted(dic.keys()):
    lst = [k] + dic[k]
    maxlen = max(len(lst), maxlen)
    ordered.append(iter(lst))

for i in range(maxlen):
    print "\t".join(next(j, '') for j in ordered)

你可以想出更简洁的格式

dic = {'Cohen'     : ['Calvino', 'Evertt', 'Borges'],
       'Larry'     : ['The Bible'],
       'Volanski'  : ['Phone Book']}

# Get max name size
mx_nm_len = len(max(dic,key=len))
mx_bk_len = max([len(max(books, key=len)) for books in dic.itervalues()])

# Store max name size + 1
mx = max([mx_nm_len, mx_bk_len]) + 1

# Store people
keys = dic.keys()

# Create generic format code to print neat list
fmat = ("%-"+str(mx)+"s")*len(keys)

# Print header line
print fmat % tuple(keys)

# similar to zip command but works for any number of lists
# Assumes all dic.values() are lists
# "zips" to longest list and uses None when any given list runs out of values
books = map(None, *dic.values())

# replaces None values in row outputs with empty strings and prints result using
# string format code (fmat)
for row in books:
    row = tuple([book if book!= None else "" for book in row])
    print fmat % row

关键是你没有以正确的方式开始定义数据。Python对第一个条目的定义方式与它的打印方式完全相同:一个字符串。如果需要多个元素,则需要将元素定义为包含多个元素:

dic = {
  'Cohen'     : ['Calvino', 'Evertt', 'Borges'],
  'Larry'     : ['The Bible'], 
  'Volanski'  : ['Phone Book']
}

现在您只需执行以下操作:

^{pr2}$

编辑好的,你没有看到你想要的名字在顶部和标题下面。有点棘手,但这可以做到:

import itertools
print "\t".join(dic.keys())
for books in itertools.izip_longest(*dic.values(), fillvalue=''):
    print "\t".join(books)

相关问题 更多 >