简体   繁体   中英

python do dictionary vertically instead of horizontally with reading csv file

so after I open a csv file with the context:

name,email,age
TOM,tom@email.com,13
BOB,bob@email.com,14
ANN,ann@email.com,15

I want to have the output like this:

{'name':['TOM','BOB','ANN'], 'email':['tom@email.com','bob@email.com','ann@email.com'], 'age':['13','14','15']}

This is my code so far, how do I get to that output?

def read_table(file_name):
open('file.csv') as lines
dic = {}
i=0
for line in lines:
    line = line.split(',')
    if line in lines[0]:
        key == line[i]
    elif line in lines[1:]:
        value == line[i]
    i+=1
    dic[key]=value
    print(dic)

Can someone please tell me where did I do wrong? Thank you

Here's another way, in case you ever want to use Pandas ( http://pandas.pydata.org )

import pandas as pd

temp = pd.read_csv("<yourNamedFile.csv")
temp.to_dict("list")

Assuming the file isn't massive you can read the whole thing into memory and use zip to switch the rows and columns.

with open("data.csv") as f:
    rows = [row.strip().split(",") for row in f]
d = {x[0]:list(x[1:]) for x in zip(*rows)}

# {'age': ['13', '14', '15'],
#  'email': ['tom@email.com', 'bob@email.com', 'ann@email.com'],
#  'name': ['TOM', 'BOB', 'ANN']}

If you don't want to use zip :

d = {x[0]:x[1:] for x in [[row[i] for row in rows] for i,_ in enumerate(rows[0])]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM