Marc Adler Marc Adler - 2 years ago 74
Python Question

Listing contents of a dictionary in two columns

I want to display a dictionary in two columns. I'm basically trying to do what this question was trying to achieve with a list, but I need to do it with a dictionary.

My script prints the directory listing for the current folder, with numbers.

Here is the script:

import os

files = os.listdir(os.curdir) #get directory listing

final_dic = dict() #initialize the dictionary

x = 1

for item in files: #associate index numbers with the filenames
final_dic[x] = item

print '''

for k, v in final_dic.iteritems(): #print out the enumerated listing
print ('{0}: {1}'.format(k, v))

num = int(raw_input('\nEnter no. of file: ')) #have user select file by no.

print ('\n{0}\n'.format(final_dic[num])) #print out corresp. filename

The output of the file listing is:


1: file1
2: file2
3: file3

The problem is that in folders with a lot of files, the listing scrolls off the top of the screen, so I would like to be able to display the listing like this:

1: file1 4: file4
2: file2 5: file5
3: file3 6: file6

From the question linked to above, it looks like
takes two lists and creates a dictionary out of them, but I've already got a dictionary.

So, is there a way to do this?

Added comment: some of the comments mention that I should use a list, but unfortunately it has to be a dictionary. This is just one part of a larger script.

Answer Source

The following uses only simple column formatting, but should at least give you an idea of how to approach the problem. Filenames are simply truncated to a maximum length to keep the columns lined-up. Note that the file number is one more than its index in the files list created, so that has to be dealt with when accepting the user's input.

from itertools import islice
import os

files = sorted(os.listdir(os.curdir))  # get directory listing

desired_cols = 2
whole_rows, partial_rows = divmod(len(files), desired_cols)
num_rows = whole_rows + (1 if partial_rows > 0 else 0)

iterators = islice(files, None), islice(files, num_rows, None)

for i, f1 in enumerate(iterators[0], start=1):
    j = i + num_rows
        f2 = next(iterators[1])
    except StopIteration:
        print('{:2d}: {:38}'.format(i, f1[:38]))  # second column empty
    print('{:2d}: {:38}  {:2d}: {:38}'.format(i, f1[:38], j, f2[:38]))

num = int(raw_input('\nEnter no. of file: '))  # have user select file by no.
index = num - 1
print ('\n{0}\n'.format(files[index]))  # print out corresp. filename
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download