Home > Software engineering >  How to create a nested dictionary with csv file
How to create a nested dictionary with csv file

Time:11-06

I want to create a nested dictionary. From a csv file (see pic) where i want to keep keys same e.g

 {'name':'john' , 'sname':'doe' , 'address':'120 Jefferson st'} ,
 {'name':'jack' , 'sname':'McGinnis', 'address':'202 hobo'}}

all the row data in one dictionay with keys as their column name.enter image description here

stuck here

CodePudding user response:

I understand you want a list of dictionaries.

import pandas as pd

data = pd.read_csv("dataset.csv")

dict_list = []
for i in range (len(data)):
  dict = {}
  for col in data.columns :
    dict[col] = data[col].iloc[i]
  dict_list.append(dict)

print(dict_list)
  • Related