简体   繁体   中英

need to fetch each row in csv file and store in a dictionary

Hi all I have a csv file where I need to iterate each row of csv and then store in a dictionary with key and values,

The Key will be the header of the CSV

for example, I have one CSV name as csv_file_data:

    sno.    val-1   val-2
      1       200      20
      2        22      44
      3        56      32
      4        32      45

form this I need the following output:

    {'csv_file_data':[{'val-1':200,'val-2':20},{'val-1':22,'val-2':44},{'val-1':56,'val-2':32},{'val-1':32,'val-2':45}]}

Hi bro,

 data_dict=[{'csvfile1_data': [{'val-1': '0', 'val-2': '0'}, {'val-1': '0', 'val-2': '0'}]}, {'csvfile2_data': [{'val-3': '138', 'val-4': '0'}, {'val-3': '0', 'val-4': '0'}]}]

 input=('input_file' [{'val-1': '100', 'val-4': '1990'}, {'val-2': '90', 'val-1': '0.0'}])

so in this, I need to replace values present in input_file with 1st list

output I needed:

 data_dict=[{'csvfile1_data': [{'val-1': '100', 'val-2': '0'}, {'val-1': '0', 'val-2': '90'}]}, {'csvfile2_data': [{'val-3': '138', 'val-4': '1990'}, {'val-3': '0', 'val-4': '0'}]}]
def get_data_csv(fn):

    mylist = []
    
    with open(fn, "r") as msg:
        for line in msg:
            mylist.append(line.strip())
        msg.close()
    
    mydict = {}
    mydict['csv_file_data'] = []
    
    headers = mylist[0].split()
    
    del mylist[0]
    
    for line in mylist:
        tmp_dict = {}
        tmp_dict[headers[1]] = int(line.split()[1])
        tmp_dict[headers[2]] = int(line.split()[2])
        mydict['csv_file_data'].append(tmp_dict)
    
    return mydict

You load your data in a list of lines mylist.

You declare your dictionary and mydict['csv_file_data'] with an empty list in.

Then you get your headers from mylist[0].split() .

Since you do not need mylist[0] you del on it.

You read the others lines in mylist , split them and load them into a temporary dict with relevant key (header).

Then you append that tmp_dict to mydict .

And you get:

{'csv_file_data': [{'val-1': 200, 'val-2': 20}, {'val-1': 22, 'val-2': 44}, {'val-1': 56, 'val-2': 32}, {'val-1': 32, 'val-2': 45}]}

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