簡體   English   中英

如何將具有3列的csv轉換為以1列為鍵,1列為其值的字典並獲取鍵的值

[英]How can I convert a csv with 3 columns to a dictionary with 1 column as key, 1 column as its value and fetch the value for key

我正在編寫一個程序來讀取和存儲給定的電子郵件ID,並將其相應的First Name存儲在數據結構中。

我在嘗試收到電子郵件ID並搜索其相應的名字后嘗試運行for循環,但它不起作用

這是我到目前為止所嘗試的:

obj=function_which_reads_email

for i in obj:
   with open('..\Project2\newcsv.csv') as file:
           data = csv.reader(file)

   df.loc=[df['Email']==i,'First_name']

始終收到相同的錯誤:

json.decoder.JSONDecodeError:行處的控制字符無效...

import pandas as pd

#First read csv pd.read_csv()
df = pd.DataFrame([['a',2],['b',4]],columns=['col1','col2'])

#value : col1 and key = col2
dictionary = {}
for i in range(len(df)):
    dictionary[df.iloc[i][0]] = df.iloc[i][1]

謝謝,但我得到了解決方案。 我將文件路徑存儲在.json文件中,然后讀取文件路徑,打開它,然后在字典中返回相應電子郵件ID的名字。

d = {} #creating dictionary

with open('signature.json') as sig:
    user = json.load(sig)                                               #load signature block of sender from json file into 'user'


path = user['File_path']                                                #storing path of input file in 'path'



with open(path,'r', newline='') as f:                                   #opening input csv file
    reader=csv.reader(f,delimiter=',')
    next(reader)

    for user_data in reader:                                            #iterating through file
        d[user_data[4]]=user_data[0]                                    #assigning name as value and  email id as key

return d     

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM