简体   繁体   English

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

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

I have the following 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], ' ')

This is the the ugly output: 这是丑陋的输出:

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

This is how I wished the output to look like: 这就是我希望输出看起来像:

Cohen      Larry       Volanski  
Calvino    The Bible   Phone Book  
Evertt  
Borgest  

(only tab-separated which I didn't manage to show here) (只有标签分隔,我没有在这里显示)

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)

You can work out neater formatting 你可以制定整洁的格式

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

The point is that you didn't define the data in the right way to begin with. 关键是你没有以正确的方式定义数据。 The way you've defined the first entry is understood by Python in precisely the way it's printed: a single string. Python定义第一个条目的方式与它的打印方式完全一致:单个字符串。 If you want multiple elements, you need to define your elements as containing multiple elements: 如果需要多个元素,则需要将元素定义为包含多个元素:

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

Now you can simply do this: 现在你可以简单地这样做:

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

Edit OK, didn't see you wanted the names across the top and titles downwards. 编辑确定,没有看到你想要顶部和标题向下的名称。 A bit trickier, but this will do it: 有点棘手,但这样做会:

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

This solution ensures the output is sorted and items wind up in the correct columns. 此解决方案可确保对输出进行排序,并使项目在正确的列中结束。 I use expandtabs() to set the tab length, to make it pretty print. 我使用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

Produces: 生产:

Cohen           Larry           Volanski       
Calvino         The Bible       Phone Book     
Evertt         
Borges 

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

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