Reputation: 29
I have the following dictionary that contains a list for each of its values
dictionary = {
0 : [2, 5]
1 : [1, 4]
2 : [3]
}
I need to output the values in a file like this
2 5
1 4
3
At the last digit of each row i need to have a space.
I have already tried to use this code
with open('test.txt', 'w') as f:
for value in dictionary.values():
f.write('{}\n'.format(value))
so i want to omit the [] and the , of the output.
I have also tried to save the values of dictionary into a lists of list and then handle list instead of dictionary. But it's not the wisest thing i guess. Numbers are also saved on wrong order and brackets and commas are save too.
a = list(dictionary.values())
for i in a:
with open('test.txt', 'w') as f:
for item in a:
f.write("%s\n" % item)
because i get this output
[3, 2]
[5, 1]
[4]
Upvotes: 0
Views: 1112
Reputation: 5237
Your first version is pretty close, so let's improve on that.
What you can do, is use a list comprehension to iterate through and convert each integer into a string. Then call join
on the resulting list of strings.
Something like the following should work:
dictionary = {
0: [2, 5],
1: [1, 4],
2: [3]
}
with open('test.txt', 'w') as f:
for value in dictionary.values():
print(' '.join([str(s) for s in value]), file=f)
Side note: I've replaced f.write
with print
, to avoid manually specifying a newline character.
If you want a trailing space character on each line, you can either do this using f-strings:
print(f"{' '.join([str(s) for s in value])} ", file=f)
or traditional string concatenation:
print(' '.join([str(s) for s in value]) + ' ', file=f)
Upvotes: 2
Reputation: 39354
I think this will give you the output you want:
a = list(dictionary.values())
with open('test.txt', 'w') as f:
for item in a:
f.write(' '.join(item) + "\n")
Update: I had better go with the idea from @deceze
Upvotes: 0