Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python dictionary with list of tuples to CSV

How can a python dictionary that looks like this:

{
    'RCLS1': [(0, 20),  (10, 112),  (20, 130), (30, 102)],
    'RCLS2': [(0, 16),(10, 53),(20, 96), (30, 45)]
}

be converted to a CSV with structure:

RCLS1,  0,  20
RCLS1, 10, 112
.
.
.
RLCS2, 30,  45

I have tried this:

with open(r'E:\data.csv', "wb") as f:
    csv.writer(f).writerows((k,) + v for k, v in dct.items())

but this resulted in the following error:

can only concatenate tuple (not "list") to tuple
like image 863
JacamoFinane Avatar asked Oct 28 '25 05:10

JacamoFinane


1 Answers

If what i understood from your question is correct, your are trying to do something like this (without the need to use of csv module):

a = {'RCLS1':[(0, 20),  (10, 112),  (20, 130), (30, 102)], 'RCLS2': [(0, 16),(10, 53),(20, 96), (30, 45)]}

with open('E:\data.csv', 'a+') as f:
    for k,v in a.items():
        f.write("{0}: {1}\n".format(k,", ".join(", ".join(str(j) for j in k) for k in v)))

Output (The date in your file will be similar to this output):

RCLS1: 0, 20, 10, 112, 20, 130, 30, 102
RCLS2: 0, 16, 10, 53, 20, 96, 30, 45

Otherwise, if you want to have the data by pair you can do something like this:

with open('E:\data.csv', 'a+') as f:
    for k,v in a.items():
        f.write("{0}: {1}\n".format(k, "".join(", ".join(str(k) for k in v))))

Output:

RCLS1: (0, 20), (10, 112), (20, 130), (30, 102)
RCLS2: (0, 16), (10, 53), (20, 96), (30, 45)

Edit:

A quick solution to your new update. You can do something like this:

a = {'RCLS1':[(0, 20),  (10, 112),  (20, 130), (30, 102)], 'RCLS2': [(0, 16),(10, 53),(20, 96), (30, 45)]}

with open('E:\data.csv', 'a+') as f:
    for k,v in a.items():
        for j in v:
            f.write("{0}: {1}\n".format(k, ", ".join(str(k) for k in j)))

Output:

RCLS2: 0, 16
RCLS2: 10, 53
RCLS2: 20, 96
RCLS2: 30, 45
RCLS1: 0, 20
RCLS1: 10, 112
RCLS1: 20, 130
RCLS1: 30, 102
like image 110
Chiheb Nexus Avatar answered Oct 29 '25 19:10

Chiheb Nexus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!