从CSV文件中读取字典并将其附加到列表中

时间:2017-11-04 21:51:58

标签: python csv dictionary

我从input()方法获取数据到我的dicts并将dicts写入一个列表。现在我想从CSV文件中读取行的数据行作为字典并将这些字典保存到列表中。

kontaktbuch = []

kontakt = {'Anrede': anrede,'Vorname': vorname_kontakt, 'Nachname': nachname_kontakt, 'Strasse': strasse, 'Hausnummer': hausnummer, 'PLZ': plz, 'Stadt' : stadt, 'Telefon1': telefon1, 'Telefon2': telefon2, 'E-Mail': email}

kontaktbuch.append(kontakt)

现在我将此方法添加到我的代码中:

def import_csv():
    with open('list.csv') as csvfile:

       reader = csv.DictReader(csvfile,delimiter=",")

       kontaktbuch.append(list(reader))

CSV文件内容:

Anrede,Vorname,Nachname,Strasse,Hausnummer,PLZ,Stadt,Telefon1,Telefon2,E-Mail
213,213,2323,2323,2323,23232,323232,23232,32323,2313
sadsad,sadad,adada,dsadasada,sadadsa,sadsada,sadsad,sadsad,asaas,ds

但是这段代码将所有的dictorinaries放在列表中的一个索引中:

[(0, [{'Strasse': '2323', 'Stadt': '323232', 'Nachname': '2323', 'Telefon1': '23232', 'PLZ': '23232', 'Anrede': '213', 'Telefon2': '32323', 'Hausnummer': '2323', 'E-Mail': '2313', 'Vorname': '213'}, {'Strasse': 'dsadasada', 'Stadt': 'sadsad', 'Nachname': 'adada', 'Telefon1': 'sadsad', 'PLZ': 'sadsada', 'Anrede': 'sadsad', 'Telefon2': 'asaas', 'Hausnummer': 'sadadsa', 'E-Mail': 'ds', 'Vorname': 'sadad'}]), (1, [{'Strasse': '2323', 'Stadt': '323232', 'Nachname': '2323', 'Telefon1': '23232', 'PLZ': '23232', 'Anrede': '213', 'Telefon2': '32323', 'Hausnummer': '2323', 'E-Mail': '2313', 'Vorname': '213'}, {'Strasse': 'dsadasada', 'Stadt': 'sadsad', 'Nachname': 'adada', 'Telefon1': 'sadsad', 'PLZ': 'sadsada', 'Anrede': 'sadsad', 'Telefon2': 'asaas', 'Hausnummer': 'sadadsa', 'E-Mail': 'ds', 'Vorname': 'sadad'}])]

使用wich方法,我可以只将dict写入列表中的一个索引吗?

1 个答案:

答案 0 :(得分:0)

完整示例:

import csv
import io

s = u"""Anrede,Vorname,Nachname,Strasse,Hausnummer,PLZ,Stadt,Telefon1,Telefon2,E-Mail
213,213,2323,2323,2323,23232,323232,23232,32323,2313
sadsad,sadad,adada,dsadasada,sadadsa,sadsada,sadsad,sadsad,asaas,ds"""

kontaktbuch = []

reader = csv.DictReader(io.StringIO(s),delimiter=",")

for row in reader:
    kontaktbuch.append(row)

# or
# kontaktbuch.extend(reader) suggested by  juanpa.arrivillaga

使用pandas:

import pandas as pd
import io

s = u"""Anrede,Vorname,Nachname,Strasse,Hausnummer,PLZ,Stadt,Telefon1,Telefon2,E-Mail
213,213,2323,2323,2323,23232,323232,23232,32323,2313
sadsad,sadad,adada,dsadasada,sadadsa,sadsada,sadsad,sadsad,asaas,ds"""

kontaktbuch = pd.read_csv(io.StringIO(s)).to_dict("r")

kontaktbuch回归:

[{'Anrede': '213',
  'E-Mail': '2313',
  'Hausnummer': '2323',
  'Nachname': '2323',
  'PLZ': '23232',
  'Stadt': '323232',
  'Strasse': '2323',
  'Telefon1': '23232',
  'Telefon2': '32323',
  'Vorname': '213'},
 {'Anrede': 'sadsad',
  'E-Mail': 'ds',
  'Hausnummer': 'sadadsa',
  'Nachname': 'adada',
  'PLZ': 'sadsada',
  'Stadt': 'sadsad',
  'Strasse': 'dsadasada',
  'Telefon1': 'sadsad',
  'Telefon2': 'asaas',
  'Vorname': 'sadad'}]