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.
Use the print() function to print a tuple in Python, e.g. print(my_tuple) . If the value is not of type tuple, use the tuple() class to convert it to a tuple and print the result, e.g. tuple([1, 2]) . Copied! We used the print() function to print a tuple's elements.
To print a list of tuples: Use a for loop to iterate over the list. Access specific elements in each tuple. Use the print() function to print the result.
You can print a tuple without parentheses by combining the string. join() method on the separator string ', ' with a generator expression to convert each tuple element to a string using the str() built-in function.
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.
You can use itertools
as well
from itertools import starmap
', '.join(starmap('{}={}'.format, a))
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, ...'
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With