1

I have a - probably - trivial question that's been bugging me for some time and I still haven't found an answer. Many of my scripts read some files, compare values from them and save these in a list or dictionary from which I then write an output file of some sort. What I always do is, I loop over the list and write the single items to my output, separated by a tab, comma, or line break. What I am always wondering is how I can prevent a separator appearing after the last item on my list has been printed.

Here is an example:

dict1 = {a: [1,2,3], b: [4,5,6], c: [7,8,9]}
for key in dict1:
    outfile.write(key +": ")
    for item in dict1[key]:
        outfile.write(str(item) +", ")
    outfile.write("\n")

The output would then look like this:

a: 1, 2, 3, 
b: 4, 5, 6, 
c: 7, 8, 9, 

How do I avoid that last ", "?

2 Answers 2

3

Use the str.join method and a list comprehesion:

for key, value in dict1.iteritems():
    outfile.write(key +": ")
    outfile.write(', '.join([str(item) for item in value]))
    outfile.write("\n")
Sign up to request clarification or add additional context in comments.

4 Comments

This works, but what may come as a surprise to the OP is that it won't necessarily be in key order... I get a, c, b for instance... (however they didn't specify it was a definite requirement)
@JonClements Thanks for that remark. Does that happen because of the list comprehension or simply because dictionaries don't preserve order?
Might even go with outfile.write("%s: %s\n" % (key, ", ".join((str(item) for item in value))))
@JonClements They are never in the order I expect, anyway. ;-)
1

What about using the standard-library CSV module?

It will handle that, plus any necessary escapint (what if one of your values includes a comma?)

(Then, of course, as general case, use string.join(list) to properly join without the trailing separator)

1 Comment

I didn't think of that because I rarely need CSV format. I will have a look. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.