0

Issue description

I want to unpack a list of tuples to a csv-file in Python 3.
The header size is fixed (4 items); the tuples are variable in size (1 to 4 items).
The unpacked tuple data should always align with the relevant header.
See examples and python code attempts below.

Question

How can I get the unpacked tuple data aligned with the fixed header, regardless of the tuple size?


Examples:

CSV-output (correct alignment between header and data)

data = [(value1, value2, value3, value4), (value1, value2, value3, value4)]

DataHeader1, DataHeader2, DataHeader3, DataHeader4
value1,      value2,      value3,      value4
value1,      value2,      value3,      value4


CSV-output (misalignment between header and data)

data = [(value1, value2, value4), (value1, value2, value4)] --> without value3

DataHeader1, DataHeader2, DataHeader3, DataHeader4
value1,      value2,      value4
value1,      value2,      value4

Should be

DataHeader1, DataHeader2, DataHeader3, DataHeader4
value1,      value2,                 , value4
value1,      value2,                 , value4



Python code (OK):

header = 'DataHeader1, DataHeader2, DataHeader3, DataHeader4'
data = [('value1','value2','value3','value4'), ('value1','value2','value3','value4')]

print(header)
print(''.join('{0},{1},{2},{3}\n'.format(a,b,c,d) for a,b,c,d in data))

Output

DataHeader1, DataHeader2, DataHeader3, DataHeader4
value1,      value2,      value3,      value4
value1,      value2,      value3,      value4



Python code (Not OK)

data = [('value1','value2', 'value4'), ('value1','value2','value4')]
print(''.join('{0},{1},{2},{3}\n'.format(a,b,c,d) for a,b,c,d in data))

Output (does not print due to tuple size mismatch)

ValueError: not enough values to unpack (expected 4, got 3)
2
  • How do we know that 'value3' is missing in the tuples, rather than value2 or value1? Is that information available somewhere, or do we just need to be told it for each set of tuples? Commented Dec 4, 2017 at 0:17
  • When tuple size is 3, then value3 is always missing. If tuple size is 2 then value 2 and 3 are always missing. Commented Dec 4, 2017 at 0:20

1 Answer 1

0

As long as you know which data is missing, you can do the following:

1) Count the number of data so that you can know if it is less than 4, using len(myTuple).

2) Creating an intermediate step to create a new tuple incorporating null values inserted at the end or wherever in the tuple data is missing. You have to create new tuples from the data you have because tuples are immutable.

3) Then you can go ahead an do the printing.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.