lawless lawless - 1 year ago 79
Python Question

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
solutions I have found work for this type of situation.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download