madik_atma
madik_atma

Reputation: 799

Read from CSV into a list with DictReader

the code:

def import_csv():

    with open('list.csv') as csvfile:
        reader = csv.DictReader(csvfile,delimiter=",")
        print(list(reader))

the Output is:

[OrderedDict([('Anrede', 'asfsf'), ('Vorname', 'dsfsdfsd'), ('Nachname', 'sdfsdfdsf'), ('Strasse', 'sdfsdfsd'), ('Hausnummer', 'sdf'), ('PLZ', 'dsf'), ('Stadt', 'dsf'), ('Telefon1', 'dsf'), ('Telefon2', 'sdf'), ('E-Mail', 'sdf')]), OrderedDict([('Anrede', '123123'), ('Vorname', '213213'), ('Nachname', '213123'), ('Strasse', '123213'), ('Hausnummer', '12312'), ('PLZ', '21323'), ('Stadt', '23'), ('Telefon1', '23'), ('Telefon2', '23'), ('E-Mail', '2')])]

My CSV file looks like:

Anrede,Vorname,Nachname,Strasse,Hausnummer,PLZ,Stadt,Telefon1,Telefon2,E-Mail
asfsf,dsfsdfsd,sdfsdfdsf,sdfsdfsd,sdf,dsf,dsf,dsf,sdf,sdf
123123,213213,213123,123213,12312,21323,23,23,23,2

I can't find a solution, why not my output is the same as at this question: Convert a csv.DictReader object to a list of dictionaries?

I want to read the lines as a dict with the header information as the keys, and then save all this together as a list.

Upvotes: 3

Views: 8819

Answers (2)

marmeladze
marmeladze

Reputation: 6564

Up to 3.6 version, DictReader generated ordinary dicts. That changed on 3.6. That's why you don't get the same result with the link you've put. Use an earlier version to get the dict. Or stick with 3.6 - OrderedDict is also great data structure to use.

Changed in version 3.6: Returned rows are now of type OrderedDict.

https://docs.python.org/3/library/csv.html#csv.DictReader

Upvotes: 3

Jean-François Fabre
Jean-François Fabre

Reputation: 140148

That's because they changed the implementation of csv.DictReader in python 3.6. What's interesting in this new implementation is that the keys are ordered like the header and it's guaranteed by the OrderedDict object (even if in Python 3.6 all dicts are ordered, but that's considered as an implementation detail so csv module doesn't rely on that)

Previously your code returned a list of dictionaries, now it returns a list or ordered dictionaries, which is one specialization.

You're worried about the representation of the data, but it will work ok, they're still dictionaries (try print(list(reader)[0]['Anrede']) for instance)

Just to reassure you just try to convert to standard dictionary:

print([dict(d) for d in reader])

you'll get

[{'Anrede': 'asfsf', 'Vorname': 'dsfsdfsd', 'Nachname': 'sdfsdfdsf', 'Strasse': 'sdfsdfsd', 'Hausnummer': 'sdf', 'PLZ': 'dsf', 'Stadt': 'dsf', 'Telefon1': 'dsf', 'Telefon2': 'sdf', 'E-Mail': 'sdf'}, {'Anrede': '123123', 'Vorname': '213213', 'Nachname': '213123', 'Strasse': '123213', 'Hausnummer': '12312', 'PLZ': '21323', 'Stadt': '23', 'Telefon1': '23', 'Telefon2': '23', 'E-Mail': '2'}]

exactly like if you were running the code on an earlier version of python.

Upvotes: 7

Related Questions