hey folks,
i'm trying myself on a csv based adressbook but I get the following error:

Traceback (most recent call last):
  File "C:\Dokumente und Einstellungen\Mo\Desktop\adressbook.py", line 11, in <module>
    writer.writerows(data)
  File "C:\Python26\lib\csv.py", line 149, in writerows
    rows.append(self._dict_to_list(rowdict))
  File "C:\Python26\lib\csv.py", line 140, in _dict_to_list
    ", ".join(wrong_fields))
ValueError: dict contains fields not in fieldnames:L,a,s,t,n,a,m,e

This is my code so far:

import csv

reader = csv.DictReader(open('adress.csv', 'rb'))

for row in reader:
    print row

writer = csv.DictWriter(open('adress1.csv', 'wb'), ['Firstname', 'Lastname', 'Phone'])
writer.writerow({'Firstname' : 'Firstname', 'Lastname' : 'Lastname', 'Phone' : 'Phone'})
data = {'Firstname' : 'Carl', 'Lastname' : 'Johnson', 'Phone' : '987651'}
writer.writerows(data)

I don't know what the error message is trying to tell me...
Do you get something out of it?

Thanks in advance.

Dani AI

Generated

Good catch — you found the symptom and fix. For future readers: the ValueError with the comma-separated letters comes from passing the wrong shape of data into DictWriter. The writer expected an iterable of row mappings (e.g., a list of dicts). Instead it got a single dict, so the writer iterated the dict’s keys (strings) and the csv internals ended up treating characters from those strings as “fields not in fieldnames,” hence the output like L,a,s,t,n,a,m,e.

Why that happens (brief): DictWriter.writerows(…) loops over the argument expecting each item to be a mapping. If you pass a plain dict it yields keys, not row mappings. If those keys are strings the code compares each character to your fieldnames and prints the characters it thinks are invalid — which looks confusing but is just a type/shape mismatch.

Practical fixes and patterns (examples):

# multiple rows: pass a sequence of dicts
rows = [
  {'Firstname':'Alice','Lastname':'Smith','Phone':'555-0101'},
  {'Firstname':'Bob','Lastname':'Jones','Phone':'555-0202'},
]
writer.writerows(rows)

# single row: either use writer.writerow(...) or wrap it in a list
writer.writerow({'Firstname':'Charlie','Lastname':'Brown','Phone':'555-0303'})
# or
writer.writerows([{'Firstname':'Charlie','Lastname':'Brown','Phone':'555-0303'}])

Extra tips: make sure the DictWriter fieldnames exactly match your dict keys (case and whitespace matter). Use writeheader() if available to emit column names. For portability, in Python 2 open CSV files in binary mode; in Python 3 open with newline='' and specify encoding. Thanks also to for the additional thread pointer.

Recommended Answers

All 2 Replies

Okay - I got it ...

writer.writerows(data)

If you want to add a single row the method is called 'writerow'

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.