I want to put the content of a csv file into dictionaries in python. I need to use them in python with functions in classes, so I have to get individual people from the dictionaries. I only need to read the csv file once, put them into seperate dictionaries and go from there. I got this code but I have no idea how to work with it; import csv

file = 'FakeNameSet.csv'
with open(file,  encoding = 'utf-8-sig') as csvfile:
    Customer_list = csv.DictReader(csvfile)
    for row in Customer_list:
        print(row)

fakenameset.csv is a file formatted like this;

Number,Gender,NameSet,GivenName,Surname,StreetAddress,ZipCode,City,EmailAddress,Username,TelephoneNumber
1,male,Dutch,Hisham,Altink,"Borkelsedijk 53","5571 GA",Bergeijk,[email protected],Reech1950,06-16898224
2,female,Dutch,Maren,Breider,"Van Humboldtstraat 130","3514 GS",Utrecht,[email protected],Othed1997,06-23093526
3,male,Dutch,Hayati,"van Dekken","Schorweg 101","5993 PC",Maasbree,[email protected],Drem1996,06-74004784

and the code above gives this output;

OrderedDict([('Number', '1'), ('Gender', 'male'), ('NameSet', 'Dutch'), ('GivenName', 'Hisham'), ('Surname', 'Altink'), ('StreetAddress', 'Borkelsedijk 53'), ('ZipCode', '5571 GA'), ('City', 'Bergeijk'), ('EmailAddress', '[email protected]'), ('Username', 'Reech1950'), ('TelephoneNumber', '06-16898224')])

It returns OrderedDict's but I have no idea what they are and how to read from it, how to get individual lines or even the names from the tuples.

1 Answers

0
GiraffeMan91 On

Each line is being returned as it's own OrderedDict as described in the docs.

You would need to store each of these somewhere to access them or process line by line.

You access them as such (from docs):

>>> import csv
>>> with open('names.csv', newline='') as csvfile:
...     reader = csv.DictReader(csvfile)
...     for row in reader:
...         print(row['first_name'], row['last_name'])
...
Eric Idle
John Cleese

>>> print(row)
OrderedDict([('first_name', 'John'), ('last_name', 'Cleese')])

So you can either do what you want to do line by line instead of print(row['column_name']) or you can store them into a list or nest them into another dictionary by a "primary key" such as number in your example:

>>> import csv
>>> data = {}
>>> with open('names.csv', newline='') as csvfile:
...     reader = csv.DictReader(csvfile)
...     for row in reader:
...         data[row['Number']] = row
>>> data[1]['GivenName']
Hisham