-1

I have the following list in Python.

[('a1',
[('b', 1),
 ('c', 2),
 ('d', 3),
 ('e', 4),
 ('f', 5),
 ('g', 6]),

('a2',
[('c', 7),
 ('f', 8),
 ('g', 9),
 ('b', 1),
 ('e', 2),
 ('d', 3)])]

I would like to save the list as the following format in csv:

a1      a2
b  1    c  7
c  2    f  8
d  3    g  9
e  4    b  1
f  5    e  2
g  6    d  3
Technologic27
  • 323
  • 2
  • 4
  • 13

2 Answers2

0

The csv format is quite simple.

To start to know how to that, just create a csv file with the output you want, and open it with any text editor, you will obtain:

a1,,a2,
b,1,c,7
c,2,f,8
d,3,g,9
e,4,b,1
f,5,e,2
g,6,d,3

So here is the code you need, but should have at least to obtain alone.

input_list = [('a1', [('b', 1), ('c', 2), ('d', 3), ('e', 4), ('f', 5), ('g', 6)]), ('a2', [('c', 7), ('f', 8), ('g', 9), ('b', 1), ('e', 2), ('d', 3)])]

with open("my_file.csv", 'w') as f:
    first_line = [x[0] + ',' for x in input_list]
    f.write(",".join(first_line) + "\n")
    for x,y in zip(input_list[0][1], input_list[1][1]):
         k1, v1 = x
         k2, v2 = y
         f.write("{k1},{v1},{k2},{v2}\n".format(k1=k1, v1=v1, k2=k2, v2=v2))

An other solution is to use the csv module. And there are some examples in the doc.

Xavier C.
  • 1,530
  • 11
  • 22
  • Use the csv module to avoid having to worry about escaping/quoting. – eddiewould Sep 13 '16 at 10:11
  • @eddiewould, I will edit my answer to add info about the csv module, but the aim of my answer was to show to OP that it's quit easy and that he should have try and should have consider IonToloaca 's solution... – Xavier C. Sep 13 '16 at 10:17
-1

This should get you started:

>>> a = [('b', 1), ('c', 2)]
>>> b = [('c', 7), ('f', 8)]
>>>
>>> for x,y in zip(a,b):
...     k1, v1 = x
...     k2, v2 = y
...     print("{k1} {v1} {k2} {v2}".format(k1=k1, v1=v1, k2=k2, v2=v2))
...
b 1 c 7
c 2 f 8
  • The format of my list is as such; [('a1', [('b', 1), ('c', 2), ('d', 3), ('e', 4), ('f', 5), ('g', 6]), ('a2', [('c', 7), ('f', 8), ('g', 9), ('b', 1), ('e', 2), ('d', 3)])] – Technologic27 Sep 13 '16 at 09:48
  • @Technologic27 You have formatted it incorrectly in the question. It is not a legitimate python list of tuples. – Little Bobby Tables Sep 13 '16 at 09:57