循环遍历字典并以特定格式打印

时间:2012-05-16 14:55:50

标签: python dictionary

我有以下字典:

# 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 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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

答案 2 :(得分: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)

答案 3 :(得分: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