Convert python dictionary to csv string.

Wanting2LearnMan used Ask the Experts™
I have a dictionary that I need to convert to a csv string.

The dictionary consists of [key, value, key, value] etc etc

How can I get all the values in the dictionary and convert it to a cvs string??

I have tried:

myCsvString = ','.join(myDict)

But I get the error:
Exception Type: TypeError
Exception Value:

sequence item 0: expected string, dict found

PLease help
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Without context and knowing exactly what you want to achieve ti's difficult to know.


a={'lastname': 'smith', 'name': 'peter'}

Open in new window

what would you expect as output?

lastname, smith, name, peter

Please note, that even the order wouldn't be guaranteed it could be either

lastname, smith, name, peter


name, peter, lastname, smith
a={'lastname': 'smith', 'name': 'peter', 'pet': 'dog'}
','.join(','.join(item) for item in a.items())

Open in new window

would result in

Open in new window

Please note, that there is a module called csv which takes care about all the proper escaping and about the different styles of csv formats.

However you should first describe exactlyhow you'd like to have your dict converted to a csv line / file

The modules doc:

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial