gpt4 book ai didi

python - 遍历字典并以特定格式打印

转载 作者:太空宇宙 更新时间:2023-11-03 14:31:09 27 4
gpt4 key购买 nike

我有以下字典:

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

# 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 - 遍历字典并以特定格式打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10621198/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com