Search code examples
pythonfilecsvdefaultdict

Write dictionary to file (CSV or TSV) where key is multiple items


How do I write a dictionary to a CSV or TSV when my data looks like this (multiple items in key):

defaultdict(<type 'list'>, {('1_719263', 35, 4): [(1, 1, 'KEEP')]})

where the key is ('1_713', 35, 4) and the value is [(1, 1, 'KEEP')].

I wanted to use json or even csv.writer.

I have also tried this:

with open (output_name, "a") as f:
    f.write(first_line + "\n")
    for key, value in x_y_output.iteritems():
        f.write(str((key, value)) + "\n")

But this does not work and I cannot get rid of the (), [], {}, etc.


Solution

  • You could try formatting your output string as a TAB separated line:

    with open (output_name, "a") as f:
        f.write(first_line + "\n")
        for key, value in my_dict.items():
            f.write("{}\t{}\n".format(key, value))
    

    Then when reading in data, you could reconstruct it using:

    new_dict = {}
    with open (output_name, "r") as f:
        for line in f:
            inline_list = line.rstrip.split('\t')
            new_dict[eval(inline_list[0])] = eval(inline_list[1])
    

    Examples in python shell:

    >>> src_dict
    {('1_719263', 35, 4): [(1, 1, 'KEEP')]}
    >>> for key, value in d.items():
    ...     outstring = "{}\t{}\n".format(k,v)
    ...     # write to file
    ... 
    >>> outstring
    "('1_719263', 35, 4)\t[(1, 1, 'KEEP')]\n"
    >>> instring = outstring.rstrip().split('\t')
    >>> instring
    ["('1_719263', 35, 4)", "[(1, 1, 'KEEP')]"]
    >>> new_dict = {}
    >>> new_dict[eval(instring[0])] = eval(instring[1])
    >>> new_dict
    {('1_719263', 35, 4): [(1, 1, 'KEEP')]}