Search code examples
pythoncsv

How to write integer values to file without quotes and parentheses


I have a dictionary with keys as a tuple, I want to write a file with no quotes and parentheses.

I tried using ",".join(map(str, key)).

import csv
d={(1, 1, 1): 600, (5, 5, 5): 700, (4, 4, 4): 800}


with open("out.csv", "wb") as f:
    w = csv.writer(f)
    for key,items in d.items():
        w.writerow([key,items])

I get this:

"(1, 1, 1)",600
"(5, 5, 5)",700
"(4, 4, 4)",800

I expect this:

1, 1, 1, 600
5, 5, 5, 700
4, 4, 4, 800

Solution

  • You need to unpack the key value to get it into list, i.e. (1,2,1) ->1,2,1 and pass this list to the writerow function.

    In your present code, [(1,1,1),600] is going as feed and it is considering it as a 2-element list, hence producing the mentioned output.

    You need to unpack the key value, i.e. [(1,1,1),600] to [1,1,1,600].

    This can be achieved by using the * operator, [*(1,1,1),600].

    Also open with w mode not wb binary mode, as you are providing the data in ASCII format not in binary format.

    import csv
    d={(1, 1, 1): 600, (5, 5, 5): 700, (4, 4, 4): 800}
    
    
    with open("out.csv", "w") as f:
        w = csv.writer(f)
        for key,items in d.items():
            w.writerow([*key,items])
    

    Otherwise, you can use this (if you do not want to unpack with *).

    import csv
    d={(1, 1, 1): 600, (5, 5, 5): 700, (4, 4, 4): 800}
    
    
    with open("out.csv", "w") as f:
        w = csv.writer(f)
        for key,items in d.items():
            lis = [i for i in key]+[items]
            w.writerow(lis)