简体   繁体   中英

Converting two column csv file data into a dictionary

I have a .tsv file with two columns of data. I want to create a dictionary where for each row, data of column 1 will be the key and data of column 2 will be the value of a dictionary. I am new to python and having trouble figuring it out.

I have tried using pandas but I am not being able to do it. It would be helpful if I can get a solution without pandas.

I am unable to separate the two columns of data and they are coming together.

Without knowing the entire setup of your problem, I can only provide a general idea to point you in the right direction, but here goes.

To load a CSV file, your best bet is Numpy's genfromtxt function, the documentation for which is at https://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html .

Let's say your data is stored in some file data.csv . We can extract your data with the following couple of lines.

import numpy as np
labels, values = np.genfromtxt('data.csv', delimiter=',', unpack=True)

This gives us two arrays, one holding label information and the other holding value information. I can do this by setting unpack=True , which separates the data in the CSV file into columns. Also, because this is a CSV file, I choose a comma to be my delimiter between entries.

Now let's create a dictionary with those arrays. This can be achieved with a simple for loop. We can iterate over labels and values in tandem using Python's zip function, which lets us do the following:

data_dict = {}
for label, value in zip(labels, values):
    data_dict[label] = value

This results in a dictionary that holds a set of values linked to a set of labels, both of which you extracted from a CSV file.

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