Dictionary of lists: writing lists (with tab separated items) to different files for each key (Python)
Dictionary of lists: writing lists (with tab separated items) to different files for each key (Python)
I have a dictionary that contains lists; the keys are based on the first item in each list. Using a fun random data set, the dictionary was constructed as follows:
import collections rand_ls = [["A","bb","cc"],["B","dd","ee"],["A","ff","gg"],["B","hh","ii"]] d = collections.defaultdict(list) for item in rand_ls: d[item[0]].append(item) print(dict(d)) # {'A': [['A', 'bb', 'cc'], ['A', 'ff', 'gg']], 'B': [['B', 'dd', 'ee'], ['B', 'hh', 'ii']]}
I want to write the lists held in each key into separate .csv files, one for each key. The closest solution I have found was detailed here, but I can't get it to work. The format I am after:
letterA.csv A bb cc A ff gg letterB.csv B dd ee B hh ii
NOTE: letter{}.csv is the unique file for each key; each list (within each key) is on a separate line, and each item within a list is separated by a tab.
The code I have is this:
for key,lists in d.items(): with open("letter{}.csv".format(key), "w") as f: f.writelines(lists, delimiter='\t')
It keeps throwing up the error: "TypeError: writelines() takes no keyword arguments". I've done some reading and I know writelines() takes a sequence of strings, so not quite sure what is missing.
Based on what I have read elsewhere, the code open("letter{}.csv".format(key), "w") should create a unique file for each key, and the subsequent line should direct the lists to be written to the appropriate file.
Answer by syrion for Dictionary of lists: writing lists (with tab separated items) to different files for each key (Python)
Read the error that you're receiving: writelines() takes no keyword arguments
. Do you see keyword arguments in your call to writelines
?
You need to join your strings together with \t
before passing them to writelines
.
Answer by Vaibhav Sagar for Dictionary of lists: writing lists (with tab separated items) to different files for each key (Python)
Try:
for key,lists in d.items(): with open("letter{}.csv".format(key), "w") as f: f.write('\t'.join(lists))
As the error message you are getting indicates, writelines
does not take keyword arguments (such as delimiter
). Since you are not writing a list to the file, but instead a string created from a list joined by a tab character, you don't even need writelines
.
Answer by tanantish for Dictionary of lists: writing lists (with tab separated items) to different files for each key (Python)
The error message is telling you that it doesn't accept keyword arguments, so if you jump to your writelines()
call, the first issue is that you're passing it a keyword param when it can't accept it. Specfically: f.writelines(lists,
delimiter='\t')
writelines
will accept a list of strings to be written to the file but you'll need to deal with all the formatting yourself if you go this route. If you wanted that I suspect you want:
for key,lists in d.items(): with open("letter{}.csv".format(key), "w") as f: f.writelines('\n'.join(['\t'.join(x) for x in l]))
Since you have a list of lists, the inner list comprehension just glues things within each list by tabs, and then the outer loop glues all of those together with end of line characters.
However just judging from the pattern and the question tags - have you considered using the CSV module, and it's associated writer method? (https://docs.python.org/2/library/csv.html)
Answer by Padraic Cunningham for Dictionary of lists: writing lists (with tab separated items) to different files for each key (Python)
The normal file.write
takes no keywords args, you are probably getting confused with and should should use the csv module which does take the delimiter
argument, iterating over d.items
, passing the k
key to str.format
and the list of lists to csv.writer.writerows
.
import csv for k, rows in d.items(): with open("letter_{}.csv".format(k), "w") as out: wr = csv.writer(out,delimiter='\t') wr.writerows(rows)
LetterA.csv:
A bb cc A ff gg
LetterB.csv:
B dd ee B hh ii
Answer by sirfz for Dictionary of lists: writing lists (with tab separated items) to different files for each key (Python)
Write a list of lines to the stream. Line separators are not added, so it is usual for each of the lines provided to have a line separator at the end.
f.writelines(["{}\n".format('\t'.join(list_)) for list_ in lists])
Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72
0 comments:
Post a Comment