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

t2a7ltrp  于 2023-05-11  发布在  其他
关注(0)|答案(1)|浏览(168)

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

但这段代码将所有字典都放在列表中的一个索引中:

[(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'}])]

用什么方法我可以写一个字典只在一个索引的名单?

pb3skfrl

pb3skfrl1#

完整示例:

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'}]

相关问题