3

我有以下字典:

# 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], ' ')

这是丑陋的输出:

Volanski    
Phone Book  
CalvinoEverttBorges  
The Bible  
Cohen   
Phone Book  
CalvinoEverttBorges  
The Bible  
Larry   
Phone Book  
CalvinoEverttBorges  
The Bible 

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

Cohen      Larry       Volanski  
Calvino    The Bible   Phone Book  
Evertt  
Borgest  

(只有制表符分隔,我没有在这里展示)

4

4 回答 4

2
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)
于 2012-05-16T15:25:04.120 回答
2

您可以制定更整洁的格式

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
于 2012-05-16T15:35:12.920 回答
1

关键是您没有以正确的方式开始定义数据。您定义第一个条目的方式被 Python 准确地理解为它的打印方式:单个字符串。如果你想要多个元素,你需要将你的元素定义为包含多个元素:

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

现在您可以简单地执行此操作:

for key, value in dic.items():
    print "%s\t%s" % (key, "\t".join(value)) 

编辑好的,没有看到您想要顶部的名称和向下的标题。有点棘手,但这会做到:

import itertools
print "\t".join(dic.keys())
for books in itertools.izip_longest(*dic.values(), fillvalue=''):
    print "\t".join(books)
于 2012-05-16T15:08:48.797 回答
0

此解决方案可确保对输出进行排序,并且项目会出现在正确的列中。我expandtabs()用来设置标签长度,使其打印得很好。

import itertools

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

sorted_keys = sorted(dic.keys())
for name in sorted_keys:
    print (name+'\t').expandtabs(15),
print
zippp = list(itertools.izip_longest(*[dic[i] for i in sorted_keys]))
for i in xrange(len(zippp[0])):
    for j in xrange(len(zippp)):
        if zippp[i][j]:
            print (zippp[i][j]+'\t').expandtabs(15),
    print

产生:

Cohen           Larry           Volanski       
Calvino         The Bible       Phone Book     
Evertt         
Borges 
于 2012-05-16T15:52:44.580 回答