2

I am trying to iterate over a dictionary in Python. The output has to resemble a certain format so it can be used as input for something else. The input looks like this:

"ok":"1",
"invalid", "0",
"unknown", "4",
...

The output should look like this:

operation,ok=1,invalid=0,unknown=4,...

I am really close to getting it with a for loop but I read that this can be done very easily with .join() in Python. Here is my code right now:

output_str = 'operation,'
for key, val in events.items():
    output_str += '{0}={1},'.format(key, val)
print output_str

Can I do this using .join? I read that join will allow me to skip the comma on the last iteration. I'm just not sure how to prepend my "operation," string to it all if I do it this way.

4
  • 7
    Simply use output_str += ','.join('{0}={1}'.format(key,val) for key,val in events.items()) to replace the entire for loop... Commented Mar 17, 2017 at 17:39
  • You dropped a ` there, Willem! edit: ok, it's up now! I think your comment is a fitting answer and so you should post it as one. Commented Mar 17, 2017 at 17:39
  • @WillemVanOnsem you should write as answer with a short explanation. this is exactly what the OP asked for and needs Commented Mar 17, 2017 at 17:42
  • Yes, thank you @WillemVanOnsem. That worked perfectly. Commented Mar 17, 2017 at 17:45

2 Answers 2

8

You can indeed use a str.join function here to join the different elements together:

output_str = 'operation,'
output_str += ','.join('{0}={1}'.format(key,val) for key,val in events.items())

Or putting it in a one-liner (and even make it shorter):

output_str = 'operation,'+','.join('{0}={1}'.format(*tup) for tup in events.items())

How does this work? As is specified in the documentation, str.join takes an iterable of strings and joins them together with the separator (here ','). So ','.join(['foo','bar','qux']) generates 'foo,bar,qux'.

Now here we use a generator. For key,value pair in events.items(), we construct a string with '{0}={1}'.format(key,val). So if key='ok' and val='1', then {0}={1}'.format(key,val) will generate ok=1. Now we join all these together.

Since str.join does not add a tailing separator, thus it meets the specifications of your question. join will usually also outperform string concatenation (in a loop).

Sign up to request clarification or add additional context in comments.

Comments

1

the function you are looking for is str.rstrip() it takes a list of characters to remove so you can do

output_str = output_str.rstrip(',')

but the solution suggested by Willem Van Onsem is better, as it avoids the issue to begin with.

Comments

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.