Reputation: 1504
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.
Upvotes: 2
Views: 2841
Reputation: 476584
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 str
ings 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).
Upvotes: 8
Reputation: 4279
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.
Upvotes: 1