0

I have an csv file that looks like

a
b
c
d
e

and a code that looks like

import csv
def func():
    with open('zumatchende.csv', mode='r') as csv_datei:
        csv_datei=csv.DictReader(csv_datei, delimiter=";", dialect="excel")
        for row in csv_datei:
            print(row)



func()

i would have expected an output like

['a']
['b']
['c']
['d']
['e']

but i get

{'a':'b'}
{'a':'c'}
{'a':'d'}
{'a':'e'}

i used this often times before and i always got the row back as an array with each element of the row as one element of the array. I dont understand why this is now formated in another data type and even puts together 2 lines into one. How can i fix this? Or what am I doing wrong? The code that i used in other places which works fine looks the same, exept the file name.

1

3 Answers 3

1

If you don't specify fieldnames when you create the DictReader, it gets the field names from the first row.

Sign up to request clarification or add additional context in comments.

Comments

1

You are trying to fetch the dictionary and printing the dictionary. Try to fetch the value instead of complete dictionary by using following code: print(list(row['a'])

Comments

1

Short answer:

with open('zumatchende.csv') as f:
    cf = csv.reader(f)
    row = [e[0] for e in cf]        
    
row

Out[14]: ['a', 'b', 'c', 'd']

Long answer:

Per the docs, DictReader outputs a dictionary whose keys are given by the optional fieldnames parameter. If fieldnames is omitted, the values in the first row of file f will be used as the fieldnames.

See a similar question here.

1 Comment

But i used this tool before and without mentioning the fieldnames. It always gave me just an array with the values from each row. Is it possible to get it like this again? since this list does not have any fieldnames

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.