Iterate over a dictionary and print it in a specific 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 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 an ugly result:

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

This is how I wanted the result to look like this:

Cohen      Larry       Volanski  
Calvino    The Bible   Phone Book  
Evertt  
Borgest  

(only tab delimiter which I failed to show here)

+3
source share
4 answers

You can format 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
+2
source
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)
+2
source

, . , , 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)
+1

, . 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 
0
source

All Articles