繁体   English   中英

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

[英]looping through a dictionary and printing it in a certain format

我有以下字典:

# 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  

(只有标签分隔,我没有在这里显示)

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']
}

现在你可以简单地这样做:

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)

此解决方案可确保对输出进行排序,并使项目在正确的列中结束。 我使用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 

暂无
暂无

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

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