Anastasia
Anastasia

Reputation: 91

How to write list elements into a tab-separated file?

I have searched the web but I haven't found the answer for my problem:

I have a a dictionary with lists as elements and every list has a different length. For example like that:

dict_with_lists[value1] = [word1, word2, word3, word4]
dict_with_lists[value2] = [word1, word2, word3]

My main problem is, that I want to write the list elements in to a file which should be tab-separated and if the list is finished it should write the new list in a new line.

I found a solution like that:

with open('fname', 'w') as file:
   file.writelines('\t'.join(i) + '\n' for i in nested_list)

But it doesn't only separate the words with tabs but also the characters.

Upvotes: 3

Views: 18977

Answers (4)

Akeem
Akeem

Reputation: 88

I think you're doing a list comprehension over the list inside of the dictionary. An alternative solution would be

with open('fname', 'w') as file:
    for nested_list in dict_with_lists.values():
        for word in nested_list:
             file.write(word + '\t')
         file.write('\n')

\I'm just looping over the values of the dictionaries, which are lists in this case and joining them using a tab and writing a newline at the end of each list. I haven't tested it but theoretically I think it should work.

Upvotes: 2

martineau
martineau

Reputation: 123453

You need to turn each list value in the dictionary into a string of tab-separated values that also have a '\n' newline character at the end of each one of them:

value1, value2 = 'key1', 'key2'
dict_with_lists = {}
dict_with_lists[value1] = ['word1', 'word2', 'word3', 'word4']
dict_with_lists[value2] = ['word1', 'word2', 'word3']

fname = 'dict_list_values.tsv'

with open(fname, 'w') as file:
    file.writelines(
        '\t'.join(values)+'\n' for values in dict_with_lists.values()
    )

Upvotes: 3

Martijn Pieters
Martijn Pieters

Reputation: 1121644

If nested_list is one of your dictionary values, then you are applying '\t'.join() to the individual words. You'd want to join the whole list:

file.write('\t'.join(nested_list) + '\n')

or, if you were to loop over the values of the dictionary:

file.writelines(
    '\t'.join(nested_list) + '\n'
    for nested_list in dict_with_lists.values())

The above uses the file.writelines() method correctly; passing in an iterable of strings to write. If you were to pass in a single string, then you are only causing Python extra work as it loops over all the individual characters of that string to write those separately, after which the underlying buffer has to assemble those back into bigger strings again.

However, there is no need to re-invent the character-separated-values writing wheel here. Use the csv module, setting the delimiter to '\t':

import csv

with open('fname', 'w', newline='') as file:
    writer = csv.writer(file, delimiter='\t')
    writer.writerows(dict_with_lists.values())

The above writes all lists in the dict_with_lists dictionary to a file. The csv.writer() object doesn't mind if your lists are of differing lengths.

Upvotes: 7

Anton vBR
Anton vBR

Reputation: 18906

Instead of jumping on an answering your question I'm going to give you a hint on how to tackle your actual problem.

There is another way to store data like that (dictionaries of non-tabular form) and it is by saving it in the JSON-string format.

import json
with open('fname','w') as f:
    json.dump(dict_with_lists, f)

And then the code to load it would be:

import json
with open('fname') as f:
    dict_with_lists = json.load(f)

Upvotes: -1

Related Questions