Reputation: 4967
I would like to write the values of a dictionary in columns of 3 to a file in python. The order of the values does not matter.
I have this dictionary dict_cols
:
dict_cols = {'1': 'c1',
'2': 'c2',
'3': 'c3',
'4': 'c4',
'5': 'c5',
'6': 'c6'}
The following code writes all the values to a text file:
with open("output.txt", "w") as f:
for k, v in dict_cols.items():
f.write(v + ", ")
output.txt
will have this content:
c1, c2, c3, c4, c5, c6,
What do I modify the code to print out the following to output.txt
in columns of 3, like the following?
c1, c2, c3,
c4, c5, c6
I am using python v3.6
Upvotes: 0
Views: 75
Reputation: 114440
The main modification to your code would be to alternate the separator between a comma and a newline. Here's one way to do that with an enumeration to keep track of your position in the sequence:
cols = 3
seps = ' ' * (cols - 1) + '\n'
with open("output.txt", "w") as f:
for i, (k, v) in enumerate(dict_cols.items()):
sep = '' if i == len(dict_cols) - 1 else ',' + seps[i % cols]
f.write(v + sep)
Upvotes: 2
Reputation: 1300
This is quite inelegant but works perfectly
dict_cols = {'1': 'c1', '2': 'c2', '3': 'c3', '4': 'c4', '5': 'c5', '6': 'c6'}
line_sep = ',\n'
with open("output.txt", "w") as f:
f.write(', '.join([v for v in dict_cols.values()][:3]) + line_sep +
', '.join([v for v in dict_cols.values()][3:]))
Upvotes: 1
Reputation:
this is my way, if I have to be honest, I would choose @Ben's answer as it's less code,more efficient and easily readable, but this is how it works. First I separate the different values of the list into the line they would be in. Then I take each value and print it.
file = "test.txt"
dict_cols = {'1': 'c1',
'2': 'c2',
'3': 'c3',
'4': 'c4',
'5': 'c5',
'6': 'c6'}
dict_values = dict_cols.values()
with open (file,"w") as f:
count = -1
sep_values = []
for ind,value in enumerate(dict_values):
if ind%3 ==0:
count+=1
sep_values.append("")
if ind != len(dict_values)-1:
end = ", "
else:
end = ""
sep_values[count] += value+end
for value in sep_values:
f.write(value+"\n")
Upvotes: 1
Reputation: 6348
This is a similar answer to @Mad Physicist's, but it doesn't use a list to hold the line endings (saves memory) and it only iterates over the values of the dictionary instead of the (unused) keys and values.
dict_cols = {'1': 'c1',
'2': 'c2',
'3': 'c3',
'4': 'c4',
'5': 'c5',
'6': 'c6'}
col = 1
with open('tmp.txt', 'w') as fp:
for i, v in enumerate(dict_cols.values()):
sep = '' if i == len(dict_cols) - 1 else ','
fp.write(v + sep)
if col == 3:
fp.write('\n')
col = 0
col += 1
Upvotes: 2