将csv读取到python(DictReader)的问题

时间:2019-04-21 18:13:51

标签: python

我想将CSV文件的内容放入python词典中。我需要在python中将它们与类中的函数一起使用,因此我必须从词典中找到个人。我只需要阅读一次csv文件,将它们放入单独的词典中然后从那里去即可。我得到了这段代码,但是我不知道如何使用它。 导入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是一个格式如下的文件:

Number,Gender,NameSet,GivenName,Surname,StreetAddress,ZipCode,City,EmailAddress,Username,TelephoneNumber
1,male,Dutch,Hisham,Altink,"Borkelsedijk 53","5571 GA",Bergeijk,HishamAltink@teleworm.us,Reech1950,06-16898224
2,female,Dutch,Maren,Breider,"Van Humboldtstraat 130","3514 GS",Utrecht,MarenBreider@dayrep.com,Othed1997,06-23093526
3,male,Dutch,Hayati,"van Dekken","Schorweg 101","5993 PC",Maasbree,HayativanDekken@teleworm.us,Drem1996,06-74004784

上面的代码给出了这个输出;

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

它返回OrderedDict,但我不知道它们是什么以及如何从中读取,如何从元组中获取单个行甚至名称。

1 个答案:

答案 0 :(得分:0)

每行都以其自己的OrderedDict形式返回,described in the 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')])

因此,您可以逐行而不是print(row['column_name'])做您想做的事情,或者可以将它们存储到列表中,也可以通过诸如“ number”之类的“主键”将它们嵌套到另一个字典中在您的示例中:

>>> 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