0

I have a dictionary that holds a two level nested list for each key that looks like the following:

OrderedDict([(0,[['a','b','c','d'],['e','f','g','h']]), (1,[['i','j','k','l'],['m','n','o','p']])])

I would like to write each nested list to a csv as a column:

a,b,c,d      e,f,g,h
i,j,k,l      m,n,o,p

the output I am getting from my current code is:

['a','b','c','d']      ['e','f','g','h']
['i','j','k','l']      ['m','n','o','p']

The columns are correct but I would like to remove the brackets [ ] and quotes ' '

a,b,c,d      e,f,g,h
i,j,k,l      m,n,o,p

CODE:

with open('test.csv', 'w', newline='') as csv_file:
    writer = csv.writer(csv_file, quotechar='"', quoting=csv.QUOTE_ALL)
    for record in my_dict.values():
        writer.writerow(record)

Any help would be appreciated!

2
  • The data structure you listed on the first line is not valid. Can you please correct? Commented Aug 8, 2013 at 4:37
  • @Trewq Fixed it. Look better? Commented Aug 8, 2013 at 4:47

2 Answers 2

1

This should work:

with open('test.csv', 'w', newline='') as csv_file:
    writer = csv.writer(csv_file, quotechar='"', quoting=csv.QUOTE_ALL)
    for record in my_dict.values():
        final = [",".join(index) for index in record]
        writer.writerow(final)
Sign up to request clarification or add additional context in comments.

1 Comment

works perfect, however, how would I deal with the record have 'n' number of indexes?
0

I am having trouble visualizing how your record looks because it seems like each value should be a nested list, meaning each column should contain both lists. If it were really writing one value from .values() at a time, it seems like you would get one column with both lists in it.

At any rate, what you want to achieve should probably be sought through the .join() method:

for record in my_dict.values():
    writer.writerow(','.join(record))

But the thing is, you're making a CSV (comma separated values) file, so each comma may be interpreted as a field-delimiter.

Question: Have you considered using a different delimiter when you instantiate your csv.writer?

4 Comments

The quoting=csv.QUOTE_ALL should quote everything written to the csv, and allow commas in the text without it being a delimiter.The record is the the entries in the OrderedDict in my post.
getting TypeError: sequence item 0: expected str instance, list found from your recommended code.
In my answer, the loop works fine, you might need to update the parameters for the writer object though.
I am remembering now: it writes out the list as a row of fields. I see how you fixed it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.