Reputation: 191
I have a list containing tuples that is generated from a database query and it looks something like this.
[(item1, value1), (item2, value2), (item3, value3),...]
The tuple will be mixed length and when I print the output it will look like this.
item1=value1, item2=value2, item3=value3,...
I have looked for a while to try to find a solution and none of the .join()
solutions I have found work for this type of situation.
Upvotes: 7
Views: 12196
Reputation: 191
One possible solution is this, definitely the shortest code
>>> a = [('val', 1), ('val2', 2), ('val3', 3)]
>>>', '.join('%s=%s' % v for v in a)
'val=1, val2=2, val3=3'
works with python 2.7 as well
Upvotes: 1
Reputation: 2311
If each tuple is only an (item, value)
pair then this should work:
l = [(item1, value1), (item2, value2), (item3, value3), ...]
', '.join('='.join(t) for t in l)
'item1=value1, item2=value2, item3=value3, ...'
Upvotes: 3
Reputation: 25662
You can use itertools
as well
from itertools import starmap
', '.join(starmap('{}={}'.format, a))
Upvotes: 3
Reputation:
If you want something like that, I would use a dictionary.
dict = {1:2,3:4}
print dict
Then, you can loop through it like this:
dict = {1:2,3:3}
print dict
for i in dict:
print i, "=", dict[i]
Hope it helps!
Upvotes: 0
Reputation: 236004
Try this:
lst = [('item1', 'value1'), ('item2', 'value2'), ('item3', 'value3')]
print ', '.join(str(x) + '=' + str(y) for x, y in lst)
I'm explicitly converting to string the items and values, if one (or both) are already strings you can remove the corresponding str()
conversion:
print ', '.join(x + '=' + y for x, y in lst)
Upvotes: 1
Reputation: 142136
You're after something like:
>>> a = [('val', 1), ('val2', 2), ('val3', 3)]
>>> ', '.join('{}={}'.format(*el) for el in a)
'val=1, val2=2, val3=3'
This also doesn't care what type the tuple elements are... you'll get the str
representation of them automatically.
Upvotes: 13