Danny Bolland Danny Bolland - 3 months ago 19
Python Question

Writing a dictionary to a csv file in python 2.7

I want to write a dictionary that looks like this:
{'2234': '1', '233': '60'}
into a new csv file that has been created.
I found a page where this was answered and I tried this out in python 2.7 but this still gives me an error whilst executing my code:

with open('variabelen.csv', 'w') as csvfile:
writer = csv.writer(csvfile)
for name, items in a.items():
writer.writerow([name] + items)


When i execute the code this shows up for me as an error:

Traceback (most recent call last):
File "/Users/Danny/Desktop/Inventaris.py", line 48, in <module>
Toevoeging_methode_plus(toevoegproduct, aantaltoevoeging)
File "/Users/Danny/Desktop/Inventaris.py", line 9, in Toevoeging_methode_plus
writecolumbs()
File "/Users/Danny/Desktop/Inventaris.py", line 24, in writecolumbs
writer.writerow([name] + items)
TypeError: can only concatenate list (not "str") to list

Answer

You are concatenating a list [name] with a string items - hence the error.

Instead, you can simply write items() via .writerows():

with open('variabelen.csv', 'w') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerows(a.items())

Given the value of a = {'2234': '1', '233': '60'}, it would produce variabelen.csv with the following content:

233,60
2234,1

The order of rows though may differ cause dictionaries in Python are unordered collections.