Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format and print list of tuples as one line

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.

like image 681
lawless Avatar asked Aug 20 '13 19:08

lawless


People also ask

How do you print a tuple from one line in Python?

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.

How do I print a list of tuples?

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.

How can I print a list of tuples without brackets?

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.


5 Answers

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.

like image 164
Jon Clements Avatar answered Nov 10 '22 09:11

Jon Clements


You can use itertools as well

from itertools import starmap
', '.join(starmap('{}={}'.format, a))
like image 20
Phillip Cloud Avatar answered Nov 10 '22 08:11

Phillip Cloud


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, ...'
like image 37
FastTurtle Avatar answered Nov 10 '22 09:11

FastTurtle


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)
like image 45
Óscar López Avatar answered Nov 10 '22 08:11

Óscar López


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

like image 26
Ati Avatar answered Nov 10 '22 08:11

Ati